Example #1
0
 def save(self):
     date = sunpy.time.parse_time(self.date)
     error = sys('touch '+self.maps_dir+'data/{:%Y/%m/%d/} > shelloutput.txt'.format(date))
     if error != 0:
         sys('{0}{1:%Y}; {0}{1:%Y/%m}; {0}{1:%Y/%m/%d} > shelloutput.txt'.format(
             'mkdir '+self.maps_dir+'data/', date))
     GenericMap.save(self, self.maps_dir+'data/{:%Y/%m/%d/%Y-%m-%dT%H:%M:%S}.fits'.format(date), clobber=True)
Example #2
0
def loadinTwo():
	while(True):
		os.sys("clear")
		time.sleep(1)
		sys.stdout.write("\r")
		sys.stdout.flush()

		sys.stdout.write("Loading")
		time.sleep(0.2)
		sys.stdout.flush()

		sys.stdout.write(".")
		time.sleep(0.2)
		sys.stdout.flush()

		sys.stdout.write(".")
		time.sleep(0.2)
		sys.stdout.flush()

		sys.stdout.write(".")
		time.sleep(0.2)
		sys.stdout.flush()

		sys.stdout.write(".")
		time.sleep(0.2)
		sys.stdout.flush()
                os.system("clear")
		sys.stdout.write("\r")
def Quitter():
    while True:
        choix=input('Veux-tu quitter ou recommencer une partie ? Q/R ')
        choix=Minuscule(choix)
        if choix=='r':
            return True
        elif choix=='q':
            sys('cls')
            print("\nDommage... :'('")
            slp(1.5)
            exit()
        else:
            print('Desole mais '+choix+' n\'est pas une reponse valide...')
Example #4
0
def metal3DToEsfBarra(nmbArch, nmbDBase, nmbTabla):
  '''
  Importa el listado de esfuerzos en barras de metal 3D que se pasa como parámetro
     nmbArchivo: Nombre del archivo que contiene el listado.
     nmbDBase: Nombre de la base de datos donde se guardará la tabla.
     nmbTabla: Nombre de la tabla que contendrá los esfuerzos.
  '''
  os.sys("fromdos " + nmbArch)
  os.sys("csplit -s "+ nmbArch + " '/.*Esfuerzos.*/' '/.*Esfuerzos.*/'")
  nmbArchEsf= nmbArch + ".esf"
  os.sys("mv xx02 " + nmbArchEsf)
  os.sys("rm -f xx*")
  metal3DcreaTablaEsfBarra(nmbArch,nmbDBase,nmbTabla)
  listado= open(nmbArchEsf,"r")
  str1= ""
  str1SB= ""
  csv= ""
  lst= []
  nmbAccion= ""
  idElem= 0.0
  numSec= 0.0
  tmpStr= ""
  tmpDbl= 0.0
  codEsf= ""
  N= 0.0
  Ty= 0.0
  Tz= 0.0
  Mt= 0.0
  My= 0.0
  Mz= 0.0
  for line in listado:
    str1= readln("listado")
    str1SB= str1.strip()
    if(strlen(str1SB)>1):
      if(re.match(".*Hipótesis.*",str1SB)):
        nmbAccion= getNombreAccion(str1SB)
      else:
        csv= replace(eliminaCar(str1SB," "),"|",",")
        if(re.match(",[0-9]+/[0-9]+.*",csv)):
          lstXSec=separaCsv(csv)
          idElem= tonum(replaceAll(lstXSec[1],"/",multINode))
          numSec= lstXSec.size-4
        else:
          if(re.match(",,[MNT].*",csv)):
            lst=separaCsv(csv)
            codEsf= getCodEsf(lst[2])
            if(codEsf=="?"):
              print "El código de esfuerzo: ",lst[2]," en la línea",str1SB," es desconocido"
            else:
              for j in range(1,numSec):
                xSec= tonum(replaceAll(lstXSec[2+j],"m",""))
                tmpDbl= lst[2+j]
                tmpStr= "update "+nmbTabla+" set " + codEsf + " = "
                tmpStr= tmpStr + sqlValue(tmpDbl) + " where ELEM= " + sqlValue(idElem)
                tmpStr= tmpStr + " and xSEC= " + sqlValue(xSec)+" and ACCION= "+sqlValue(nmbAccion)
                cur.execute(tmpStr)
  listado.close()
Example #5
0
def AvoidWrongTriggers():
    """ Throws an error if Eyelink is connected but not configured.\n
    *Only needed in EEG experiments without Eyetracking!*

    **Author** : Wanja Mössing, WWU Münster | [email protected] \n
    *July 2017*

    Since we use a Y-cable which is supposed to send the TTL-triggers from
    the Python-PC to EEG & Eyetracker host, there is a permanent
    connection between the three parallelports (1. EEG, 2.Python, 3.Eyelink).
    Therefore, all parallelports need to be set low, except for the one
    putting the triggers (i.e. Python). The Eyelink host-pc sends a random
    trigger at startup if not configured properly. So if an experiment that
    doesn't use the Eyetracker sends a trigger to the EEG while the
    Eyetracker host-pc is turned on, that causes a wrong trigger in the EEG
    signal. This function can be placed at the beginning of an
    experiment that doesn't use the eyelink to throw an error if the eyelink
    is still connected.
    """
    from os import system as sys
    from platform import system as sys_name
    print 'Pinging Eyelink to check if connected and powered...'

    if sys_name() == 'Windows':
        r = sys('ping -n 1 100.1.1.1')
    else:
        r = sys('ping -c 1 100.1.1.1')

    if r != 0:
        msg = """Eyelink host PC is turned on. Without running the appropriate
        startup routines (e.g., `EyelinkStart` from Wanja`s Github repo),
        this will cause faulty triggervalues in your EEG signal, because the
        parallel-port of the Eyelink-PC is set to a random value at startup
        instead of reading the port. Either turn off the Eyelink-PC or
        configure it!"""
        print(msg)
        raise SystemExit
    return
def pol_rec():
	os.system('cls')
	global pi
	global e
	global cont
	print("This is a polar to rectangular vector converter.")
	time.sleep(1)
	while cont not in ["n","N"]:
		while True:
			try:
				angle_type = input("Is the angle in radians: y or n>>")
				print("Enter the vector in the format shown below:\n magnitude,angle")
				mag,angle= input("Please enter the polar vector>>").split(',')
				mag = float(mag)
				angle = float(angle)
				if angle_type in ["n","N","no","No"]:
					angle = math.radians(angle)
				x_vec = mag*math.cos(angle)
				y_vec = mag*math.sin(angle)
				print("<{},{}>".format(x_vec,y_vec))
				break
			except:
				print("Error: Invalid Input!")
				time.sleep(1)
				os.system('cls')
		while True:
			cont = input("Do you wish to continue:Y or N?>>")
			if cont in ["y","Y"]:
				break
			elif cont in ["n", "N"]:
				break
			else:
				print("Error: Invalid Input")
				time.sleep(1)
				os.system('cls')
		os.sys('cls')
Example #7
0
def metal3DcreaTablaEsfBarra(nmbArch, nmbDBase, nmbTabla):
  '''
  Importa el listado de esfuerzos en barras de metal 3D que se pasa como parámetro
     nmbArchivo: Nombre del archivo que contiene el listado.
     nmbDBase: Nombre de la base de datos donde se guardará la tabla.
     nmbTabla: Nombre de la tabla que contendrá los esfuerzos.
  '''
  os.sys("fromdos " + nmbArch)
  os.sys("csplit -s "+ nmbArch + " '/.*Esfuerzos.*/' '/.*Esfuerzos.*/'")
  nmbArchEsf= nmbArch + ".esf"
  os.sys("mv xx02 " + nmbArchEsf)
  os.sys("rm -f xx*")
  SQLTcreaTabla(nmbDBase,nmbTabla,"(idSecc int,ACCION string,ELEM integer,xSEC double,AXIL double,Q_1 double,Q_2 double,M_1 double,M_2 double,TORSOR double)")
  listado= open(nmbArchEsf,"r")
  str1= ""
  str1SB= ""
  csv= ""
  lst= []
  lstXSec= ""
  nmbAccion= ""
  idElem= 0.0
  idSecc= 0.0
  numSec= 0.0
  xSec= 0.0
  tmpStr= ""
  j= 0.0
  listado= open(nmbArchEsf)
  for line in listado:
    str1= line
    str1SB= str.strip()
    if(strlen(str1SB)>1):
      if(re.match(".*Hipótesis.*",str1SB)):
        nmbAccion= getNombreAccion(str1SB)
        for j in range(1,numSec):
          xSec= tonum(replaceAll(lst[2+j],"m",""))
          idSecc= idElem*10+j
          cur.execute("insert into "+nmbTabla+" (idSecc,ACCION,ELEM,xSEC) values("+sqlValue(int(idSecc))+","+sqlValue(nmbAccion)+","+sqlValue(idElem)+","+sqlValue(xSec)+")")
      else:
        csv= replace(eliminaCar(str1SB," "),"|",",")
        if(re.match(",[0-9]+/[0-9]+.*",csv)):
          lst=separaCsv(csv)
          idElem= tonum(replaceAll(lst[1],"/",multINode))
          numSec= lst.size-4
  listado.close()
Example #8
0
NDiv = 1
'''
#Test
MaxFiles=2
NDiv=1
'''

cnt = 0
for fr in range(0, MaxFiles, NDiv):
    to = fr + NDiv
    for iev in range(0, Njobperfile):
        #if(cnt>5) : break
        #sys("rm ./output/output_%d_%d" %(fr,to))
        #sys("rm -rf ./log/log_%d_%d" %(fr,to))
        #print "We now delete log"
        sys("mkdir ./log/log_%d_%d_%d" % (fr, to, iev))
        Logfile = "./log/log_%d_%d_%d" % (fr, to, iev)
        Filenm01 = "%s/FBasy_%d_%d_%d.job" % (Logfile, fr, to, iev)
        Filenm02 = "%s/FBasy_%d_%d_%d.sh" % (Logfile, fr, to, iev)

        sys("cp ~/condor_script4 %s" % Filenm01)
        sys("echo \"Output          = %s/Corrjob.out\">>%s" %
            (Logfile, Filenm01))
        sys("echo \"Error           = %s/Corrjob.err\">>%s" %
            (Logfile, Filenm01))
        sys("echo \"Log             = %s/Corrjob.log\">>%s" %
            (Logfile, Filenm01))
        sys("echo \"Executable      = %s\">>%s" % (Filenm02, Filenm01))
        sys("echo \"Queue\"                        >>%s" % Filenm01)

        sys("echo \"#!/bin/sh    \">%s" % Filenm02)
#!/usr/bin/env python3

from os import system as sys
sys("clear")
print("\n\n[ Info ] [ Wait ] Intalling Requeriments...\n\n")
sys("./requeriments.sh")

from requests import get
from simplejson.errors import JSONDecodeError
from time import sleep

url_lunesnode = 'https://github.com/Lunes-platform/LunesNode/releases/download/0.0.7/lunesnode-latest.jar'
url_wallet_generator = "https://github.com/Lunes-platform/WalletGenerator/releases/download/0.0.1/walletgenerator.jar"


def set_name():
    return input("\n[ Info ] Write your node name? ")


def set_ip():
    print("\n[ Info ] [ Wait ] Looking for your IP...\n")
    x = get("https://ifconfig.me").text
    option_ip = input(f"[ Info ] This [ {x} ] is your IP address? [y/n] ")

    if option_ip == "y":
        return x

    elif option_ip == "n":
        ip = input("\n[ Info ] Input your ip: ")
        return ip
Example #10
0
player2 = Player(input("Player 2: Please enter a name: "), 2)
started = unixtime()

def getInput(player):
    prefix = "{} (Player {})".format(player.name, player.number)
    inp = input("{}: Please input 'Rock', 'Paper' or 'Scissors': ".format(prefix)).lower()

    if inp not in ["rock", "paper", "scissors"]:
        print("{}: Try again.".format(prefix))
        getInput(player)
    
    return inp

while True:
    p1_inp = getInput(player1)
    sys("cls")
    p2_inp = getInput(player2)

    winner = check_inputs(player1, player2, p1_inp, p2_inp)

    if winner == "p1": player1.matches_won += 1
    elif winner == "p2": player2.matches_won += 1

    try_again = input("Do you want to try again or both player's statistics? Enter 'Yes' to try again, 'viewstats' to view your statistics and anything else to exit. ").lower()

    if try_again == "yes":
        print("Starting a new game!")
        continue
    elif try_again == "viewstats":
        date1 = datetime.fromtimestamp(started)
        date2 = datetime.fromtimestamp(unixtime())
Example #11
0
            
            p13.start(100)
            p18.start(100)

            forward=100
            backward=0

try:
    char = screen.getch()
    if char == ord('p'):
        LastKey='p'
        time.sleep(0.5)
        camera.capture('/home/pi/Documents/lucru/YoloV2NCS/data/image_captura_%s.jpg' %captura)
        print ('Captura initializata')
        print ('\n')
        sys("cd YoloV2NCS && python3 ./detectionExample/Main.py --image ./data/image_captura_%s.jpg" % captura)
        print ('Captura completa!%s imagini captate\n' %captura)
        captura+=1
        print ('\n')
    elif char == ord(' '):
        LastKey=' '
        Stop()
        GPIO.output(20,True)
        GPIO.output(21,True)
        time.sleep(0.5)
        GPIO.output(20,False)
        GPIO.output(21,False)
        time.sleep(0.5)
    elif char == curses.KEY_RIGHT:
        Right()
    elif char == curses.KEY_LEFT:
Example #12
0
def Bagger(datastoredir):
    if datastoredir == "./MalwareAPK":
        TYPE = 1  # TYPE SET TO DIFFERENTIATE MALWARE AND BENIGN IN DATASET WITH LABELS
        print("\n\t ** Extracting From Malware Samples ** \n\n")
    elif datastoredir == "./BenignAPK":
        TYPE = 0
        print("\n\t ** Extracting From Benign Samples ** \n\n")
    TimeStamp = str(time.time())
    Flag = 1

    # Jdax = "./Modules/jadx/bin/jadx"
    # Jdax = "./jadx/build/jadx/bin/jadx"
    Jdax = "./jadx/build/jadx/bin/jadx"
    TargetApkPath = datastoredir + "/"
    ApkNameList = os.listdir(datastoredir)
    if len(ApkNameList) == int(0):
        Flag = 0

    if Flag != int(0):
        ApkNameList.sort()
        TotalApks = len(ApkNameList)
        CurrentApk = 0
        fieldnames = []
        with open('data.csv') as csv_file:
            CSVREADER = csv.DictReader(csv_file)
            fieldnames = CSVREADER.fieldnames  #GET THE FIELD NAMES

        csv_master_dict = dict.fromkeys(fieldnames, 0)

        for ApkName in ApkNameList:
            TargetApk = TargetApkPath + ApkName

            print(">[" + str(CurrentApk + 1) + ' / ' + str(TotalApks) +
                  "] --- " + ApkName,
                  end=' ')
            print("\t.", end=' ')
            sys(Jdax + " -d ./UnpackedApk/" + ApkName + TimeStamp + " " +
                TargetApk +
                " >/dev/null")  #EXTRACT THE PERMISSIONS FROM THE APK FILES
            print(".", end=' ')

            UnpackedDir = "./UnpackedApk/" + ApkName + TimeStamp
            MainfestPath = UnpackedDir + "/resources/AndroidManifest.xml"

            try:
                root = ET.parse(MainfestPath).getroot()  # FORMAT DATA ROW
                permissions = root.findall("uses-permission")
                csv_master_dict = dict.fromkeys(fieldnames, 0)
                csv_master_dict['NAME'] = ApkName
                csv_master_dict['CLASS'] = TYPE
                for perm in permissions:
                    for att in perm.attrib:
                        permelement = perm.attrib[att]
                        if permelement in defaultList:
                            csv_master_dict[permelement] = 1
                sys("rm -f -R " + UnpackedDir)
                print(".", end=' ')
                with open('data.csv', 'a') as csv_dump:
                    CSVwriter = csv.DictWriter(csv_dump, fieldnames=fieldnames)
                    CSVwriter.writerow(
                        csv_master_dict
                    )  # SAVE DATA TO DATASET ROW BY ROW FOR EACH APPLICATION
                print(".")
            except Exception:
                print("EERRRROORR")
                pass
            CurrentApk += 1
    choix_jouer=Minuscule(choix_jouer)
    if choix_jouer=='oui':
        break
    elif choix_jouer=='non':
        print("Dommage... :'(")
        slp(1.5)
        exit()
    else:
        print('Desole mais '+Entree+' n\'est pas une reponse valide...')

while True:

    not_alone=Multi()

    while int(Diff)==0:
        sys('cls')
        print('Choisis ta difficulte : ')
        print('\n1)Facile')
        print('2)Moyen')
        print('3)Difficile')
        print('4)Personnalise')
        Diff=input()

        #On essaye de convertir Diff en Integer. Si ca marche pas, c'est que
        #le joueur a mis des lettres, et ca lui dit
        try:
            Diff=int(Diff)
        except Exception as e:
            print('Il semblerait que tu n\'ais pas renseigne un nombre...')
            continue
Example #14
0
def getFTPFile(login):

    chamada = (
        'lftp -p %s -u %s,%s -e "get %s;quit" %s' %
        (login.porta, login.usuario, login.senha, login.arquivo, login.ip))
    sys(chamada)
Example #15
0
def clear(sclear, clearcmd):
    if (sclear == True):
        sys(clearcmd)
    else:
        print('\n', end='')
Example #16
0
from os import system as sys
import msvcrt
while (True):
    print('Programa de sumas')
    num1 = int(input('Ingrese el primer numero:'))
    num2 = int(input('Ingrese el segundo numero:'))
    print('Que quieres hacer?')
    print('1.Sumar los 2 numeros')
    print('2.Restar los 2 numeros')
    print('3.Multiplicar los 2 numeros')
    num = (int(input('Elige un numero:')))
    if (num == 1):
        print('La suma da:', num1 + num2)
        print("Presione una tecla para continuar...")
        msvcrt.getch()
        sys('cls')
    elif (num == 2):
        print('La resta da:', num1 - num2)
        print("Presione una tecla para continuar...")
        msvcrt.getch()
        sys('cls')
    elif (num == 3):
        print('La multiplicacion da', num1 * num2)
        print("Presione una tecla para continuar...")
        msvcrt.getch()
        sys('cls')
    else:
        print('Opcion invalida')
                    |    _--''   __--*"__-'`
                    |_--"  .--=`"__-||"
                    |      |  |\\\\   ||
                    | .dUU |  | \\\\ //
                    | UUUU | _|___//
                    | UUUU |  |
                    | UUUU |  |
                    | UUUU |  |
                    | UUUU |  |
                    | UUUU |  |
                    | UUP' |  |
                    |   ___^-"`
                     ""'
""")
                sleep(5)
                sys('cls')
                print('\nOh non t\'as croise le videur !')
                print('Ils ont pris tout ton pognon, et ils t\'ont bute !')
                Continuer=False
                break
            else:
                print('\nPutain la chance ! Il etait pas la ! Le temps de changer')
                print('de vetements et tu reviens, personne ne te reconnait. Tu as %s euros.'%Argent)
        else:
            Argent=Argent-mise*2
            print('\nZut ! Tu n\'as plus que %s euros...'%Argent)

        cont=input('\nOn continue ? Oui/Non ')
        cont=fonctions.Minuscule(cont)
        if cont!='oui' and cont!='non':
            print('Ta reponse n\'est pas valide !')
Example #18
0
    of = open("file.log", "a")
    time1 = time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(time.time()))
    if new == old:
        of.write("{} {}\n".format(alias, time1))


#fun2("www.baidu.com", "baidu")
#在每月初进行备份
copy_time = time.strftime('%d', time.localtime(time.time()))
if copy_time == 1:
    shutil.copy("file1.log", "file2.log")
    shutil.copy("file.log", "file1.log")

of = open("m3u81.conf")
lists = of.readlines()
list_temp = []
for h in lists:
    if h.strip():
        list_temp.append(h)
lists = list_temp[:]
l = len(lists)
if l <= 0:
    os.sys("clear")
    print("[Warning]Please add the host server")

while 1:
    for i in range(0, l):
        v_list = lists[i].strip().split(" ")
        if fun1(v_list[0], v_list[1]) == 0:
            fun2(v_list[0], v_list[1])
Example #19
0
def print_header():
    sys("clear")
    print(header)
Example #20
0
#!/usr/bin/env python
#automatically run PredictHaplo

import os 
import sys
import glob
import string 

#generate config
listsample = open('listsample.txt','r')
for i in range(0,16):
  os.sys('cp config_sim0 config_sim'+str(i+1))
  samplename = listsample.xreadline().rsplit()
  os.sys('sed \'3s/.*/'+samplename+'/\' config_sim'+str(i+1)+' > config.tmp1')
  os.sys('sed \'5s/.*/ref.fa/\' config.tmp1 > config.tmp2')
  os.sys('sed \'9s:.*:data/'+samplename+'_R1aaaa.sam:\' config.tmp2 > config.tmp3')
  os.sys('sed \'11s/.*/0/\' config.tmp3 > config_sim'+str(i+1))
  os.sys('./PredictHaplo config_sim'+str(i+1))
Example #21
0
def addHost():
    nome = ""
    ip = ""
    user = ""
    senha = ""
    protocolo = ""
    porta = 0

    while True:
        nome = input("\nnome do equipamento -> ")
        if nome != "":
            break
        else:
            sys('echo "$(tput setaf 1)\n  O NOME NAO PODE ESTAR EM BRANCO \n$(tput sgr0)"'
                )
    while True:
        ip = input("IP do equipamento -> ")
        if ip != "":
            break
        else:
            sys('echo "$(tput setaf 1)\n  O IP NAO PODE ESTAR EM BRANCO \n$(tput sgr0)"'
                )

    while True:
        user = input("usuario do equipamento -> ")
        if user != "":
            break
        else:
            sys('echo "$(tput setaf 1)\n  O USUARIO NAO PODE ESTAR EM BRANCO \n$(tput sgr0)"'
                )

    while True:
        senha = input("senha do equipamento -> ")
        if senha != "":
            break
        else:
            sys('echo "$(tput setaf 3)\n  DESEJA REALMENTE DEIXAR A SENHA EM BRANCO? \n$(tput sgr0)"'
                )
            op = input(" (Y/N) -> ")
            if op.upper() == "Y":
                break
    while True:

        op = input(
            "\nMetodo de backup:\n1 - FTP (via lftp)\n2 - SSH (via scp)\n --> "
        )

        if op == "1":
            protocolo = "FTP"
            break
        elif op == "2":
            protocolo = "SSH"
            break
        else:
            sys('echo "$(tput setaf 1)\n  OPCAO INVALIDA \n$(tput sgr0)"')

    while True:
        default_port_number = "21"
        if protocolo == "SSH":
            default_port_number = "22"

        try:
            porta = input("porta do equipamento (%s default) -> " %
                          (default_port_number))
            if porta != "":
                porta = int(porta)
            break
        except:
            sys('echo "$(tput setaf 1)\n  POR FAVOR, APENAS DIGITOS \n$(tput sgr0)"'
                )

    new_login = Modelos.Login(utils.tratarNome(nome), ip, user, senha, porta,
                              "backup.rsc", protocolo)

    banco.insert(new_login)

    sys('echo "$(tput setaf 2)\n  EQUIPAMENTO ADICIONADO COM SUCESSO \n$(tput sgr0)"'
        )
Example #22
0
import os

proxyflag = ""
if os.sys("env | grep proxy")==0:
	proxyflag = "-E"

os.sys("sudo " + proxyflag + " apt-get install build-essential python-pip python-dev python3-dev libevent-dev python-all-dev python-scipy python-matplotlib python-numpy portaudio19-dev libatlas-base-dev gfortran multimedia-jack libpng-dev libjpeg-dev libfreetype6-dev")
os.sys("sudo " + proxyflag + " pip3 install scipy pyaudio ")
os.sys("sudo " + proxyflag + " pip3 install pylab")

# To start recording :P
"""
Listening requires:
You may need to change "pcm.front cards.pcm.front" to "pcm.front cards.pcm.default" in /usr/share/alsa/alsa.conf.
jack_control dps period 64
dbus-launch jack_control start


Try this from the command line:

pulseaudio --kill  
jack_control  start
Then when your done do this:

jack_control exit  
pulseaudio --start
And sometimes jack wont die, so then do

Get jackd's PID:

ps -aux | grep jackd  
Example #23
0
# -*- coding: utf-8 -*-
# Samet BELLUR

from os import system as sys

values = list(range(5))
tab = "\n"  # I need that because backslash cannot useable in f-string.

for i in range(5):
    x = input("Varriable {}: ".format(i + 1))
    try:
        values[i] = int(x)
    except ValueError:
        try:
            values[i] = float(x)
        except ValueError:
            values[i] = x

sys("cls")

for i in range(5):
    print(
        f'{tab}Varriable {i+1};{tab}Value: {values[i]}{tab}Type: {type(values[i])}'
    )

sys("pause")
Example #24
0
def execute_step(index):
    print "Now executing '{0}'...".format(steps.keys()[index])
    sys(steps.values()[index])
    print "Execution of '{0}' complete".format(steps.keys()[index])
from os import system as sys
count = 0
while count <= 20:
    sys("python3 multi.py")
Example #26
0
import os

os.sys("python listenSensi.py")
# os.sys("python amplitude.py")
os.sys("python fft.py")
def get_image(url):
    nome_arquivo = url.split('/').pop()
    print(nome_arquivo)
    command = "curl --output " + nome_arquivo + " " + url
    sys(command)
    print("feito!")
Example #28
0
    if b == a:
        les_joueurs[i].send("déplacement incorrect ,rejouez".encode("Utf8"))
        time.sleep(1)
        continue

    #Lorsque le joueur i a gagné
    if a == "vous gagnez":
        les_joueurs[i].send(a.encode("Utf8"))
        message = "joueur " + str(i) + " a gagné"
        for joueur in liste_joueur:
            if joueur != les_joueurs[i]:
                joueur.send(message.encode("Utf8"))
                joueur.close()
        time.sleep(1)
        break
        
    message = "joueur " + str(i) + " a joué \n" + a
    for key in les_joueurs:
        les_joueurs[key].send(message.encode("Utf8"))
    time.sleep(1.5)
    i += 1
    #On réinitialise i si i est supérieur au nombre de joueur
    if i > nb_joueur:
        i = 1

try:
    os.sys("pause")
except:
    print("le jeu est términé")
    
Example #29
0
    )
    exit()

try:
    import rcpy
#	print("\nRCPY is installed!")
except ImportError:
    print("\nRCPY is not installed!")

    permission = input(
        "Should I install the missing packages for you? (y/n): ")

    if permission.lower == "y":
        print("Installing missing packages!")
        os.sys(
            "sudo apt-get update && sudo apt-get install roboticscape -y && sudo apt-get upgrade roboticscape -y && sudo apt-get install python3 python3-pip -y && sudo pip3 install rcpy && sudo pip3 install numpy"
        )

        # Configure Network

        change_ap_ssid = input("Change the AP SSID? (y/n): ")

        if change_ap_ssid.lower == "y":

            ap_ssid = input("Enter new SSID: ")

        elif change_ap_ssid.lower == "n":

            pass

        change_ap_pass = input("Change the AP password? (y/n): ")
from os import system as sys
import getpass
from termcolor import colored
from python_operations import what_py
from docker_operations_all import what_docker
from all_operations import all_operations_display
import smtplib

#code for banner and designs
print(sys("figlet LINUXPY"))
print()
print()

#read password from file
f = open("password.txt",'r')
password = f.read()
password = password[0:len(password)-1]

#password setup
x = getpass.getpass("Enter Your Password : "******"LogIn Successfull !","red"))
	print()
else :
	print(colored("Password is Incorrect !","red"))

#menu-bar
first_time = True
if x == password:
	while True:
Example #31
0
import os
try:
    from mysql.connector import errorcode
except ImportError:
    from os import system as sys
    sys("pip install mysql-connector-python")
    del sys

try:
    from prettytable import PrettyTable
except ImportError:
    from os import system as sys
    sys("pip install prettytable && exit")
    del sys

import mysql
import mysql.connector
from mysql.connector import errorcode

import mysql.connector
cnx = mysql.connector.connect(user="******", password="******", host="localhost")
cur = cnx.cursor()
s1 = "CREATE DATABASE SCAMAZON"
cur.execute(s1)

s = "use SCAMAZON"
cur.execute(s)

s2 = "create table Cart(Ino VARCHAR(10),Mno VARCHAR(10),Price int,QTY INT)"
cur.execute(s2)
Example #32
0
from os import system as sys

sys('''
gcc -c IA.c
gcc -c functions.c
gcc -c main.c
gcc -o exe main.o functions.o IA.o
rm *.o
./exe
''')


Example #33
0
from os import system as sys

sys("ifconfig")
sys("sudo ifconfig eth0 down")
sys("sudo ifconfig eth0 192.168.41.33")  #original ip is 192.168.43.130
sys("sudo idconig eth0 up")
def set_files(node_name, ip, type_net, hash_seed, password):
    sys(f"sed -i 's/NODE_NAME/{node_name}/g' ./settings/lunesnode.conf")
    sys(f"sed -i 's/IPV4/{ip}/g' ./settings/lunesnode.conf")
    sys(f"sed -i 's/TYPE_NETWORK/{type_net}/g' ./settings/lunesnode.conf")
    sys(f"sed -i 's/WALLET_SEED/{hash_seed}/g' ./settings/lunesnode.conf")
    sys(f"sed -i 's/WALLET_PASS/{password}/g' ./settings/lunesnode.conf")
    sys(f"sed -i 's/PEER1/5.189.132.164:7770/g' ./settings/lunesnode.conf")
    sys(f"sed -i 's/PEER2/51.195.255.104:7770/g' ./settings/lunesnode.conf")
    sys(f"sed -i 's/PEER3/104.248.112.173/g' ./settings/lunesnode.conf")
Example #35
0
#### neeed to make sure google still work for sure
# this may have to run on non-python devs' boxes, try/catch an install of the requests lib to be SURE

try:
    import requests
except:
    import os
    os.sys('easy_install pip')
    os.sys('pip install requests')
    import requests

#r = requests.get('http://www.google.com/')
r = requests.get('http://google.com')

if r.status_code = 200:
    print "yep, it still there"
Example #36
0
                count += 1

        if count != 0:
            conn = pymysql.connect(host='127.0.0.1',
                                   user='******',
                                   passwd=None,
                                   db='development_sdn')
            cur = conn.cursor()
            cur.execute(
                "INSERT INTO t_sdnfetchedinformation(noOfSdnRecordsFetched) VALUES ('{}')"
                .format(count))
            conn.commit()
            # conn.close()
            print('done')

            sql = "SELECT sdnFetchedInformationUid FROM t_sdnfetchedinformation WHERE noOfSdnRecordsFetched='{}'".format(
                count)
            cur.execute(sql)
            allInfo = cur.fetchall()
            for all in allInfo:
                for one in all:
                    batch = one

            print(batch)
            # time.sleep(5)
            sdn_trigger(file_name, batch)


main()
sys('rm {}'.format(file_name))
Example #37
0
import numpy as np
import datetime as dt
import sunpy
from sunpy.net import vso
from sunpy.map import Map, GenericMap
from sunpy.instr.aia import aiaprep
from scipy.io.idl import readsav as read
from astropy import units as u
from os import system as sys
#import numexpr as ne
try:
    from fits import calc_fits
except ImportError:
    print 'Current extension is broken, missing or incompatible.\n'\
        +'Compiling Fortran extension.'
    sys('f2py -c -m fits fitsmodule.f90')
    from fits import calc_fits

home = '/media/huw/'

def gaussian(x, mean=0.0, std=1.0, amp=1.0):
    """Simple function to return a Gaussian distribution"""
    if isinstance(x, list):
        x = np.array(x)
    power = -((x - mean) ** 2.0) / (2.0 * (std ** 2.0))
    f = amp * np.exp(power)
    if amp == 1:
        f = f / max(f)
    return f

Example #38
0
from os import system as sys
import time

# Instructions #
# Replace 'access_key and secret_key with your keys
# Add/remove or adjust any of the below commands
# The structure is there to help you with the command syntax.

start = time.time()
sys('navi keys --a access_key --s secret_key')

sys('echo Adding User Groups')
# Create User Groups
sys('navi usergroup new --name "Linux" >> user_navi.log')
sys('navi usergroup new --name "Corporate Apps" >> user_navi.log')
sys('navi usergroup new --name "Custom Apps" >> user_navi.log')
sys('navi usergroup new --name "Software" >> user_navi.log')

sys('echo creating users')
# Create or enable users
sys('navi user add --username "*****@*****.**" --password "Dietcoke\!12345" --permission 64 --name "Thor" --email "*****@*****.**" >> user_navi.log'
    )
sys('navi user add --username "*****@*****.**" --password "Dietcoke\!12345" --permission 64 --name "Hulk Smash" --email "*****@*****.**" >> user_navi.log'
    )
sys('navi user add --username "*****@*****.**" --password "Dietcoke\!12345" --permission 64 --name "IronMan" --email "ironman@@marvel.avengers" >> user_navi.log'
    )
sys('navi user add --username "*****@*****.**" --password "Dietcoke\!12345" --permission 64 --name "Spiderman" --email "*****@*****.**" >> user_navi.log'
    )
sys('navi user add --username "*****@*****.**" --password "Dietcoke\!12345" --permission 64 --name "Dr Strange" --email "*****@*****.**" >> user_navi.log'
    )
Example #39
0
def getSCPFile(login):
    chamada = ('sshpass -p "%s" scp -P %s %s@%s:/%s %s' %
               (login.senha, login.porta, login.usuario, login.ip,
                login.arquivo, login.arquivo))
    sys(chamada)
Example #40
0
#!/usr/bin/python
from os import system as sys
from collections import OrderedDict

def init():
    sys("mkdir ../temp")

def shutdown():
    #sys("rm -r ../temp")
    pass

steps = OrderedDict()
steps["copy-workspace"] = "cp -R ../../workspace/* ../temp/"
steps["copy-resources"] = "cp -R ../resources/* ../temp/"
#steps["create-archive"] = "zip -rv ../../bin/$(date +output.%F.%T.crx) ../temp/*"

def execute_step(index):
    print "Now executing '{0}'...".format(steps.keys()[index])
    sys(steps.values()[index])
    print "Execution of '{0}' complete".format(steps.keys()[index])

init()
i = 0
while i < len(steps):
    execute_step(i)
    i += 1
shutdown()

#sys("echo All steps done. Target built at output.$(date +%F.%T).crx")
sys("echo All steps done. Extension folder is at $(cd ..; pwd)/temp")
Example #41
0
 def cmd(self):
     self = raw_input('Secure-Shell=> ')
     sys(self)
Example #42
0
def init():
    sys("mkdir ../temp")
Example #43
0
def init():
	sys("sudo amixer cset numid=3 1")
Example #44
0
def banner():
    sys("cat banner.txt")
Example #45
0
from os import system as sys
try:
    from termcolor import colored
    from time import sleep
    import socket
except ModuleNotFoundError:
    sys("python install.py")
sys("clear")


def banner():
    sys("cat banner.txt")


try:
    print("\033[1;31;40m")
    banner()
    print("\t \t\t<[----- coded By ansanbinoy -----]>")
    print("")
    g = (colored("[~]", 'green'))
    y = ("\033[1;35m[+]")
    c = (colored("[~]", 'cyan'))
    b = (colored("[~]", 'blue'))
    gm = (colored("[-]", 'green'))
    tip = input(gm + " \033[1;32mTarget host : \033[1;37m")
    print("")
    tport = input(gm + " \033[1;32mPort range [Eg:(80-90) :\033[1;37m ")
    lport = int(tport.split('-')[0])
    rport = int(tport.split('-')[1])
    hport = rport + 1
    print(colored("<===================================>", 'white'))
Example #46
0
def calculate_temperatures(date, n_params=1, data_dir=home+'SDO_data/',
                            maps_dir=home+'temperature_maps/', n_procs=4):
    wlens = ['94', '131', '171', '193', '211', '335']
    client = vso.VSOClient()
    print 'Finding data for {}.'.format(date.date())
    # Loop through wavelengths
    for wl, wlen in enumerate(wlens):
        #print 'Finding {}A data...'.format(wlen),
        fits_dir = data_dir + '{}/{:%Y/%m/%d}/'.format(wlen, date)
        filename = fits_dir + 'aia*{0}*{1:%Y?%m?%d}?{1:%H?%M}*lev1?fits'.format(wlen, date)
        temp_im = Map(filename)
        # Download data if not enough found
        if temp_im == []:
            print 'File not found. Downloading from VSO...'
            qr = client.query(vso.attrs.Time(date,# - dt.timedelta(seconds=6),
                                             date + dt.timedelta(seconds=12)),#6)),
                              vso.attrs.Wave(wlen, wlen),
                              vso.attrs.Instrument('aia'),
                              vso.attrs.Provider('JSOC'))
            res = client.get(qr, path=fits_dir+'{file}', site='NSO',
                             methods=['URL_FILE_Rice']).wait()

    n_wlens = len(wlens)
    temp = np.arange(5.6, 7.01, 0.01)
    n_temps = len(temp)
    if n_params == 1:
        wid = [0.1]
        hei = [1.0]
    else:
        wid = np.arange(0.1, 1.1, 0.1) # Just copying Aschwanden's range here
        hei = np.arange(15, 31)
    n_widths = len(wid)
    n_heights = len(hei)
    n_vals = n_temps * n_widths * n_heights
    
    try:
        #raise IOError
        model = np.memmap(filename=home+'synth_emiss_{}pars'.format(n_params),
                          dtype='float32', mode='r', shape=(n_vals, n_wlens))
        params = np.loadtxt(home+'gaussian_parameters_{}'.format(n_params))
    except IOError:
        resp = load_temp_responses()
        logt = np.arange(0, 15.05, 0.05)
        delta_t = logt[1] - logt[0]
        model = np.memmap(filename=home+'synth_emiss_{}pars'.format(n_params),
                          dtype='float32', mode='w+', shape=(n_vals, n_wlens))
        params = np.zeros((n_vals, n_params))
        # Define linear index in model for this set of parameters
        i = 0
        #   For given gaussian width, height and centre:
        for width in wid:
            for height in hei:
                for meantemp in temp:
                    # For each channel k:
                    # intensity(k, params) <- sum(temperature_response(k, params) * DEM(params)) * dT
                    dem = gaussian(logt, float(meantemp), width, height)
                    model[i, :] = np.sum(resp * dem, axis=1) * delta_t
                    normmod = model[i, 2]
                    model[i, :] = model[i, :] / normmod
                    # Store these parameters for use later
                    params[i, :] = [meantemp, width, height]
                    i += 1
        model.flush()
        np.savetxt(home+'gaussian_parameters_{}'.format(n_params), params)

    sys('mpirun -np {} -host localhost python parallel_ext.py {}T{} {} {}'.format(
            n_procs, date.date(), date.time(), n_params, n_vals))
    
    return
Example #47
0
def hasPing(host):
    ping_str = "ping -c 1 > /dev/null"
    resposta = sys(ping_str + " " + host)
    return resposta == 0
Example #48
0
from credentials import username,password,server
from os import system as sys

sys( "sqlplus {}/{}@{}".format(username,password,server) )

Example #49
0
    def compare(self, display_wlen='171', context_wlen=None, extra_maps=[]):
        #        temp_args=None, temp_kwargs=None,
        #        wlen_args=None, wlen_kwargs=None,
        #        ctxt_args=None, ctxt_kwargs=None,
        #        extr_args=None, extr_kwargs=None):
        valid_wlens = ['94', '131', '171', '195', '211', '335', '304', 'hmi']
        if display_wlen.lower() not in valid_wlens:
            print "Display wavelength provided invalid or None."
            output = self.plot()#*temp_args, **temp_kwargs)
            return output
        save_output = True
        data_dir = self.data_dir
        maps_dir = self.maps_dir
        
        date = self.date
        nmaps = 2 + len(extra_maps)
        if context_wlen:
            nrows = 2
        else:
            nrows = 1
        
        fig = plt.figure(figsize=(24, 14))
        
        fig.add_subplot(nrows, nmaps, nmaps, axisbg='k')
        self.plot()#*temp_args, **temp_kwargs)
        plt.colorbar(orientation='horizontal')
        
        displaymap = Map(data_dir+'{0}/{1:%Y/%m/%d}/aia*{0}*t{1:%H?%M}*lev1?fits'\
            .format(display_wlen, date))
        if isinstance(displaymap, list):
            displaymap = displaymap[0]
        displaymap = aiaprep(displaymap)
        displaymap /= displaymap.exposure_time
        
        fig.add_subplot(nrows, nmaps, 1, axisbg='k')
        displaymap.plot()#*wlen_args, **wlen_kwargs)
        plt.colorbar(orientation='horizontal')
        
        if context_wlen and self.region != None:
            context_plot = fig.add_subplot(nrows, 1, nrows)
            contextmap = Map(data_dir+'{0}/{1:%Y/%m/%d}/aia*{0}*t{1:%H?%M}*lev1?fits'.format(context_wlen, date))
            if isinstance(contextmap, list):
                contextmap = contextmap[0]
            x, y = self.region_coordinate['x'], self.region_coordinate['y']
            contextmap = contextmap.submap([-1000, 1000], [y-300, y+300])
            # Need to figure out how to get 'subimsize' from self. Use the default 150'' for now
            #rect = patches.Rectangle([x-subdx, y-subdx], subimsize[0], subimsize[1], color='white', fill=False)
            rect = patches.Rectangle([x-150, y-150], 300, 300, color='white',
                                     fill=False)
            contextmap.plot()#*ctxt_args, **ctxt_kwargs)
            context_plot.add_artist(rect)
        
        for m, thismap in extra_maps:
            fig.add_subplot(nrows, nmaps, 3+m)
            thismap.plot()#*extr_args, **extr_kwargs)
        
        if save_output:
            error = sys('touch '+maps_dir+'maps/{:%Y/%m/%d/} > shelloutput.txt'.format(date))
            if error != 0:
                sys('{0}{1:%Y}; {0}{1:%Y/%m}; {0}{1:%Y/%m/%d} > shelloutput.txt'\
                        .format('mkdir '+maps_dir+'maps/', date))
            filename = maps_dir+'maps/{:%Y/%m/%d/%Y-%m-%dT%H:%M:%S}_with{}'.\
                    format(date, display_wlen)
            plt.savefig(filename)
            if self.region != None:
                reg_dir = maps_dir + 'maps/region_maps'
                reg_dir = reg_dir + '/{}/'. format(self.region)
                error = sys('touch ' + reg_dir + ' > shelloutput.txt')
                if error != 0:
                    sys('mkdir ' + reg_dir + ' > shelloutput.txt')
                plt.savefig(reg_dir+'{:%Y-%m-%dT%H:%M:%S}'.format(date))
            plt.close()
        else:
            plt.show()

        return
Example #50
0
def left():
	sys("sudo aplay left.wav")
Example #51
0
def backward():
	sys("sudo aplay backward.wav")
Example #52
0
def forward():
	sys("sudo aplay forward.wav")
Example #53
0
def mk_file(name):
    '''
    这个方法只用来创建空文件,只接受一个参数:文件的名字
    '''
    sys('touch %s' % name)
Example #54
0
def right():
	sys("sudo aplay right.wav")
Example #55
0
                print "Error inesperado\n"
        elif opciones_ac[accion] == 'descripcion':
            codigo = int(
                raw_input('Introduzca el código del producto a modificar:\n'))
            descripcion = raw_input(
                "Introduzca la nueva descripción del producto:\n") or ""
            if descripcion:
                descripcion = "descripcion='{}'".format(descripcion)
                cur.execute(
                    "UPDATE productos SET {0} WHERE codigo={1};".format(
                        descripcion, codigo))
                conn.commit()
                cur.close()
                conn.close()

        elif opciones_ac[accion] == 'salir':
            sys('clear')
            print "\nPrograma terminado.\n"
            cur.close()
            conn.close()
            return

        raw_input("\n\n\n\tPresione enter para continuar...")
        sys('clear')
        continue


if __name__ == '__main__':
    sys('clear')
    main()
Example #56
0
def mk_dir(name):
    '''
    这个方法只创建文件夹,只接受一个参数:文件夹的名字
    '''
    sys('mkdir %s' % name)
Example #57
0
def main():
    while True:
        dbname = 'tienda'
        user = raw_input("Introduzca el nombre de usuario: ")
        pwd = 'password'
        #host = 'localhost'
        host = raw_input("Introduzca el host: ")

        try:
            db_usr = "******".format(
                dbname, user, host, pwd)
            conn = psycopg2.connect(db_usr)

        except Exception:
            pprint("Error:")
            logging.basicConfig(format="%(message)s")
            logging.warning("Unable to connect")
            return

        cur = conn.cursor()
        opciones_depa = {
            1: 'lacteos',
            2: 'perfumeria',
            3: 'jardin',
            4: 'abarrotes',
        }
        opciones_ac = {
            1: 'consultar',
            2: 'insertar',
            3: 'modificar',
            4: 'perecedero',
            5: 'descripcion',
            0: 'salir',
        }
        departamento = int(
            raw_input("""Introduzca el número del departamento a acceder:
            1 - Lácteos
            2 - Perfumería
            3 - Jardín
            4 - Abarrotes

    >>"""))
        sys('clear')
        accion = int(
            raw_input("""Introduzca la opción deseada:
            1 - Consultar productos
            2 - Insertar registro
            3 - Modificar nombre de producto
            4 - Mostrar perecederos
            5 - Modificar descripción
            0 - Regresar

    >>"""))
        sys('clear')

        if opciones_ac[accion] == 'consultar':
            try:
                cur.execute("SELECT codigo, nombre,\
                            descripcion FROM productos\
                            WHERE departamento = '{}';".format(
                    opciones_depa[departamento]))
                print "Código\tNombre\t\tDescripción\n"
                for x in cur.fetchall():
                    print x[0], "\t", x[1], "\t\t", x[2]
            except:
                print "Error inesperado\n"

        elif opciones_ac[accion] == 'insertar':
            try:

                nombre = raw_input("Introduce el nombre del producto:\n")
                departamento = raw_input("Introduce el departamento:\n")
                descripcion = raw_input("Introduce la descripción:\n")
                perecedero = 's' in raw_input("Perecedero(s/n)\n").lower()
                proveedor = raw_input("Introduce el proveedor(10 char)\n")[:10]
                cur.execute(
                    "INSERT INTO productos(nombre,departamento,descripcion,perecedero,proveedor)\
                            values('{0}','{1}','{2}',{3},'{4}');".format(
                        nombre, departamento, descripcion, perecedero,
                        proveedor))
                conn.commit()
                cur.close()
                conn.close()
            except:
                print "Error inesperado\n"

        elif opciones_ac[accion] == 'modificar':
            codigo = int(
                raw_input('Introduzca el código del producto a modificar:\n'))
            nombre = raw_input(
                "Introduzca el nuevo nombre del producto:\n") or ""
            departamento = raw_input(
                "Introduzca el nuevo nombre de departamento:\n") or ""
            descripcion = raw_input(
                "Introduzca la nueva descripción del producto:\n") or ""

            if nombre:
                nombre = "nombre='{}'".format(nombre)
                cur.execute("UPDATE productos SET {0} WHERE departamento='{1}'\
                            AND codigo={2};".format(
                    nombre, opciones_depa[departamento], codigo))
                conn.commit()
                cur.close()
                conn.close()
        elif opciones_ac[accion] == 'perecedero':
            try:
                cur.execute("SELECT codigo,nombre\
                            FROM productos\
                            WHERE perecedero=True\
                            AND departamento='{0}';".format(
                    opciones_depa[departamento]))
                print "Código\tNombre\n"
                for x in cur.fetchall():
                    print x[0], "\t", x[1]
            except:
                print "Error inesperado\n"
        elif opciones_ac[accion] == 'descripcion':
            codigo = int(
                raw_input('Introduzca el código del producto a modificar:\n'))
            descripcion = raw_input(
                "Introduzca la nueva descripción del producto:\n") or ""
            if descripcion:
                descripcion = "descripcion='{}'".format(descripcion)
                cur.execute(
                    "UPDATE productos SET {0} WHERE codigo={1};".format(
                        descripcion, codigo))
                conn.commit()
                cur.close()
                conn.close()

        elif opciones_ac[accion] == 'salir':
            sys('clear')
            print "\nPrograma terminado.\n"
            cur.close()
            conn.close()
            return

        raw_input("\n\n\n\tPresione enter para continuar...")
        sys('clear')
        continue
Example #58
0
import os
import time
counter=0
while True:
    try:
        os.sys('python /home/kim/codes/150322final.py')
        counter+=1
        print 'application runs for'+str(counter)+'times'
        time.sleep(5)
    except:
        print 'error occurred'
Example #59
0
# Run this file only when you are absolutely sure

from os import system as sys
from WebsiteData import main_pages, Main_Folders

sys('rm ./temp.html')

for folder in Main_Folders:
    # run this command to check the files to be deleted
    # system(f'find ./{folder} -name "*.html" -type f')

    # run this command to delete the files after checking
    sys(f'find ./{folder} -name "*.html" -type f -delete')
    sys(f'find ./{folder} -name "*.txt" -type f -delete')

for page in main_pages:
    # run this command to check the files to be deleted
    # system(f'ls ./{page}')

    # run this command to delete the files after checking
    sys(f'rm ./{page}')