Example #1
0
def test_motors():
    # DC motor test!
    m1.run(Adafruit_MotorHAT.BACKWARD)
    m2.run(Adafruit_MotorHAT.FORWARD)
    m3.run(Adafruit_MotorHAT.BACKWARD)
    m4.run(Adafruit_MotorHAT.FORWARD)
    time.Sleep(.25)
    m1.run(Adafruit_MotorHAT.FORWARD)
    m2.run(Adafruit_MotorHAT.BACKWARD)
    m3.run(Adafruit_MotorHAT.FORWARD)
    m4.run(Adafruit_MotorHAT.BACKWARD)
    time.Sleep(.25)
    turn_off_motors()
def get_semantic_scholar_metadata(scirex_ids, scirex_s2orc_mappings, overwrite_cache=False):
    s2orc_metadata_cache_file = os.path.join(caches_directory, "s2_metadata.pkl")
    if os.path.exists(s2orc_metadata_cache_file) and not overwrite_cache:
        metadatas = pickle.load(open(s2orc_metadata_cache_file, 'rb'))
    else:
        # Manually hit the SemanticScholar API to get entries (takes about 5 minutes)
        metadatas = {}
        for i, scirex_id in enumerate(scirex_ids):
            if scirex_id in scirex_s2orc_mappings:
                s2orc_id = scirex_s2orc_mappings[scirex_id].doc_id
                if s2orc_id != "":
                    simple_s2_metadata = S2Metadata(str(s2orc_id),
                                    None,
                                    None,
                                    None,
                                    None,
                                    None)
                    metadatas[scirex_id] = simple_s2_metadata
                    continue

            # Remap a few SciREX paper ids known to be bad:
            if scirex_id == "0c278ecf472f42ec1140ca2f1a0a3dd60cbe5c48":
                api_url = f"https://api.semanticscholar.org/v1/paper/9f67b3edc67a35c884bd532a5e73fa3a7f3660d8"
            elif scirex_id == "1a6b67622d04df8e245575bf8fb2066fb6729720":
                api_url = f"https://api.semanticscholar.org/v1/paper/f0ccb215faaeb1e9e86af5827b76c27a8d04e5a7"
            else:
                api_url = f"https://api.semanticscholar.org/v1/paper/{scirex_id}"

            r = requests.get(api_url)
            if r.status_code == 429:
                # Sleep 100 seconds and retry, in case we've hit the service rate limiter
                while True:
                    print("Too many requests error!")
                    time.Sleep(100)
                    r = requests.get(api_url)
                    if r.status_code != 429:
                        break
            #
            response = r.json()        
            # Verify that all fields are in response
            keys = ["corpusId", "paperId", "title", "doi", "arxivId", "url"]
            for k in keys:
                if k not in response:
                    print(f"SciREX document {i} missing key {k}")
                    break
            #
            s2_metadata = S2Metadata(str(response.get("corpusId")),
                                    response.get("paperId"),
                                    response.get("title"),
                                    response.get("doi"),
                                    response.get("arxivId"),
                                    response.get("url"))
            metadatas[scirex_id] = s2_metadata
            if (i+1) % 10 == 0:
                print(f"{i+1} document metadatas downloaded")
            # Rate-limit
            time.sleep(3)
        pickle.dump(metadatas, open(s2orc_metadata_cache_file, 'wb'))

    return metadatas
Example #3
0
 def StarterPopulation(self, p):
     counter: int = 0
     while counter < 10:
         try:
             p.arkOne.AddNewAnimal("Tiger", "Carnivore", "Rainforest")
             p.arkOne.AddNewAnimal("Panda", "Herbivore", "Rainforest")
             p.arkOne.AddNewAnimal("Chimp", "Omnivore", "Rainforest")
             p.arkOne.AddNewAnimal("Zebra", "Herbivore", "Savannah")
             p.arkOne.AddNewAnimal("Lion", "Carnivore", "Savannah")
             p.arkOne.AddNewAnimal("Antilop", "Herbivore", "Savannah")
             p.arkOne.AddNewAnimal("Wolf", "Carnivore", "Temperate Forest")
             p.arkOne.AddNewAnimal("Beaver", "Herbivore",
                                   "Temperate Forest")
             p.arkOne.AddNewAnimal("Bald Eagle", "Carnivore",
                                   "Temperate Forest")
             p.arkOne.AddNewAnimal("Polar bear", "Carnivore", "Arctic")
             p.arkOne.AddNewAnimal("Seal", "Carnivore", "Arctic")
             p.arkOne.AddNewAnimal("Penguin", "Carnivore", "Arctic")
             p.arkOne.AddNewAnimal("Dolphin", "Carnivore", "Sea")
             p.arkOne.AddNewAnimal("Turtle", "Herbivore", "Sea")
             p.arkOne.AddNewAnimal("Seagull", "Herbivore", "Sea")
             counter += 1
         except HabitatNotExistException:
             ToolBox.WriteLineRed("Habitat is not exist!")
             time.Sleep(1500)
def testGetPosition():
	arm = ArmController()
	while(true):
		position = arm.getPostion()
		x = position[0]
		y = position[1]
		print("x: " + str(x) + ",y: " + str(y))
		print("")
		time.Sleep(1) # delay one second
 def LifeCycle(self, p, cycleTime):
     while True:  #not readchar. Console.KeyAvailable:
         os.system("Clear")
         p.arkOne.ResourceCycle()
         ShowAnimals(p)
         ShowRequiredResources(p)
         ShowResourceGenerators(p)
         p.arkOne.BirthDay()
         p.arkOne.Dying()
         time.Sleep(cycleTime)
Example #6
0
 def SubChoiceHabitat(self, p):
     choice: str = ToolBox.InputAny("Choose an option: ")
     print()
     if choice == "1":  # Creating new habitat
         try:
             newName: str = ToolBox.InputAny(
                 "The name of the new Habitat?: ")
             if p.arkOne.IsHabitatExist(newName):
                 raise HabitatIsExistException
             p.arkOne.CreatingAHabitat(newName)
             ToolBox.WriteLineGreen("Tha habitat has been built.")
         except HabitatIsExistException:
             ToolBox.WriteLineRed("This Habitat is already exist")
         time.Sleep(1500)
     elif choice == "2":  # Displaying Habitats
         for habitat in p.arkOne.GetHabitats():
             ToolBox.WriteBlue(habitat.HabitatName + ": ")
             print(habitat.AnimalList.Count.ToString() +
                   " animals live in this Habitat.")
         ToolBox.InputAny("Press any key to continue...")
     elif choice == "3":  # Renaming a Habitat
         try:
             habitatName: str = ToolBox.InputAny(
                 "The name of the Habitat?: ")
             newName: str = ToolBox.InputAny(
                 "The new name of the Habitat?: ")
             if p.arkOne.IsHabitatExist(newName):
                 raise HabitatIsExistException()
             habitats = p.arkOne.GetHabitats()
             for habitat in habitats:
                 if not p.arkOne.IsHabitatExist(newName):
                     habitat.SetHabitatName(newName)
                     ToolBox.WriteLineGreen("The Habitat has been renamed.")
         except HabitatNotExistException:
             ToolBox.WriteLineRed("This Habitat is not exist")
         except HabitatIsExistException:
             ToolBox.WriteLineRed("This Habitat is already exist")
         time.sleep(1500)
     elif choice == "4":  # Deleting a Habitat
         try:
             p.arkOne.RemovingAHabitat(
                 ToolBox.InputAny("The name of the habitat?: "))
             ToolBox.WriteLineGreen("The Habitat has been demolished.")
         except HabitatNotExistException:
             ToolBox.WriteLineRed("This Habitat is not exist")
         except NotEmptyHabitatException:
             ToolBox.WriteLineRed(
                 "You can not demolish because animals live there")
         time.sleep(1500)
     elif choice == "0":  # Back to main menu
         return False
     else:
         ToolBox.WriteLineRed("Wrong option!")
     return True
Example #7
0
def Said(chan, user, msg):
    print chan, user, msg
    #if 'mkbot' in msg:
    if ((("gundam" or "this mod") and "illegal") in msg) and (timer < 5):
        b = random.randint(1, 5)
        spring.Say('gundam', "Gundam is perfectly legal, you deluded jerk!")
        users[user] = 2
        timer + 1 = timer
        if timer == 4:
            spring.Say('gundam', "This is below me...")
            time.Sleep(30)
            timer = 0
Example #8
0
 def test_cmd_SET(self):
     sent = self.client.send(bytearray("SET", 'utf-8'))
     msgB = self.client.recv(3)
     msg = msgB.decode()
     assert msg == "ack"
     msg = "RS,1;LI,1;UI,1;SP,1;SV,1;TF,1"
     msgB = bytearray(msg, 'utf-8')
     sent = self.client.send(msgB)
     tt.Sleep(1)
     self.serverLock.acquire()
     while not self.serverLock.isEmpty():
         msg = self.serverQ.get()
         msgS = msg.aplit(",")
         assert len(msgS) == 2
         print(msgS)
Example #9
0
def request_api(question):
    url = api_url + api_port + api_route
    payload = {"question": question}

    response_data = ""
    while response_data == "":
        try:
            print "ISSUING POST REQUEST..."
            session = requests.Session()
            req = session.post(url, data=payload, timeout=15)
            response_data = str(req.text)
        except:
            print "Connection timeout..."
            print "Retrying post request..."
            time.Sleep(1)
            continue
    
    response_data = json.JSONDecoder().decode(response_data)
    return response_data["answer"]
Example #10
0
                fmt.Fprintf(conn, "final")
                flag := read()
                fmt.Printf("decoding flag of size %d: %x\n", len(flag), flag)

                fmt.Fprintf(conn, "final")
                tag := read()
                fmt.Printf("with tag of size %d: %x\n", len(tag), tag)

                ciphertext := append(flag, tag...)
                fmt.Printf("final cipher of size %d: %x\n", len(ciphertext), ciphertext)

                block, _ := aes.NewCipher(key)
                aesgcm, _ := cipher.NewGCM(block)

                plaintext, err := aesgcm.Open(nil, iv, ciphertext, nil)
                if err != nil {
                        fmt.Println("failed to decode with err: " + err.Error())
                        time.Sleep(time.Second)
                        continue
                }

                sha := sha256.Sum256(plaintext)
                hash := hex.EncodeToString(sha[:])
                if hash == checksum {
                        fmt.Println(string(plaintext))
                        break
                }
                fmt.Println("didn't match checksum")
        }
}
Example #11
0
def tickTock(timePipe):
    while True:
        time.Sleep(.01)
        if timePipe.recv() == "*":
            timePipe.send(time.clock())
Example #12
0
def StartDrag():
    s = GetCursorPosition();
    xpos = s.x;
    ypos = s.y;
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0)
    time.Sleep(randint(70, 130));
Example #13
0
 def SubChoiceAnimal(self, p):
     choice = ToolBox.InputAny("Choose an option: ")
     print()
     if choice == "1":  # Adding new animals
         typeo: str = ""
         speciesName = ToolBox.InputAny("What is the species?: ")
         habitatName = ToolBox.InputAny(
             "What is the optimal habitat zone?: ")
         while True:
             typeo = ToolBox.InputAny(
                 "What kind of animal is this? (herbivore, carnivore, omnivore): "
             )
             if typeo.ToLower() == "herbivore" or typeo.ToLower(
             ) == "carnivore" or typeo.ToLower() == "omnivore":
                 break
         specimen: int = ToolBox.InputInt("How many animals arrived?: ")
         try:
             for count in range(specimen):
                 p.arkOne.AddNewAnimal(speciesName, type, habitatName)
         except HabitatNotExistException:
             ToolBox.WriteLineRed(
                 "This Habitat is not exist. You should build it first!")
             time.Sleep(1500)
     elif choice == "2":  #Listing an animal
         animaL: Animal
         try:
             animaL = p.arkOne.FindAnimal(
                 ToolBox.InputAny("What is the ID of the animal?: "))
             print("The animal ID is: " + animaL.OwnName)
             print("The animal species is: " + animaL.SpeciesName)
             print("Required energy: " + animaL.ReqEnergyUnit)
             print("Required heat: " + animaL.ReqHeatUnit)
             print("Required oxigen: " + animaL.ReqOxigenUnit)
             print("Required water: " + animaL.ReqWaterUnit)
             print("Required food: " + animaL.ReqFoodUnit)
         except AnimalNotExistException:
             ToolBox.WriteLineRed("There is no such animal...")
         ToolBox.InputAny("Press any key to continue...")
     elif choice == "3":  #Listing all animal
         for habitat in p.arkOne.GetHabitats():
             ToolBox.WriteLineBlue(habitat.HabitatName)
             for animal in habitat.AnimalList:
                 print("ID: " + animal.OwnName.PadRight(4))
                 print(" " + animal.SpeciesName.PadRight(15))
                 print(" RE: " + animal.ReqEnergyUnit)
                 print(" RH: " + animal.ReqHeatUnit)
                 print(" RO: " + animal.ReqOxigenUnit)
                 print(" RW: " + animal.ReqWaterUnit)
                 print(" RF: " + animal.ReqFoodUnit)
         print("Press any key to continue...")
         ToolBox.InputAny()
     elif choice == "4":  #Update an animal
         try:
             animaL = p.arkOne.FindAnimal(
                 ToolBox.InputAny("What is the ID of the animal?: "))
             print("The animal ID is: " + animaL.OwnName)
             print("The animal species is: " + animaL.SpeciesName)
             print("Required energy: " + animaL.ReqEnergyUnit)
             print("Required heat: " + animaL.ReqHeatUnit)
             print("Required oxigen: " + animaL.ReqOxigenUnit)
             print("Required water: " + animaL.ReqWaterUnit)
             print("Required food: " + animaL.ReqFoodUnit)
             print()
             ToolBox.WriteLineRed(
                 "The parameters should be between 1 and 4")
             print()
             animaL.ReqEnergyUnit = ToolBox.InputIntBetween(
                 "New required energy?: ", 1, 4)
             animaL.ReqHeatUnit = ToolBox.InputIntBetween(
                 "New required heat ?: ", 1, 4)
             animaL.ReqOxigenUnit = ToolBox.InputIntBetween(
                 "New required oxigen?: ", 1, 4)
             animaL.ReqWaterUnit = ToolBox.InputIntBetween(
                 "New required water?: ", 1, 4)
             animaL.ReqFoodUnit = ToolBox.InputIntBetween(
                 "New required food?: ", 1, 4)
             print("The parameters of this animal has updated")
         except AnimalNotExistException:
             ToolBox.WriteLineRed("There is no such animal...")
         time.Sleep(1500)
     elif choice == "5":  #Removing an animal
         try:
             p.arkOne.RelocateAnimal(
                 ToolBox.InputAny(
                     "What is the ID of the animal you want to relocate?: ")
             )
             ToolBox.WriteLineGreen("The animal has relocated.")
         except AnimalNotExistException:
             ToolBox.WriteLineRed("There is no such animal...")
         time.Sleep(1500)
     elif choice == "0":
         return False
     else:
         ToolBox.WriteLineRed("Wrong option!")
     return True
Example #14
0
def Battlephase():
    global Attacks
    global BossHealth
    CurrentBossHealth = BossHealth

    ActionTaken = False

    while ActionTaken == False:
        try:
            Action = int(
                input(
                    'Enter 1 to Attack. Enter 2 to use an item in your Inventory: '
                ))
            time.sleep(0.5)
            print()
            if Action == 1:
                ValidAttack = False
                while ValidAttack == False:
                    for index in range(0, len(Attacks)):
                        print('Enter', index, 'for', Attacks[index])
                    time.sleep(0.5)
                    print()
                    try:
                        Attack_Select = int(
                            input('Enter the number for your attack: '))
                        time.sleep(0.5)
                        print()
                        Attack = Attacks[Attack_Select]

                        if Attack == 'SpitBall':
                            time.sleep(0.5)
                            print('Spit Ball!')
                            print()
                            time.sleep(0.5)
                            print(
                                'Your chewed up paper hits them in the face and does 15 damage.'
                            )
                            BossHealth = CurrentBossHealth - 15
                            print()
                            return BossHealth

                        if Attack == 'Kick':
                            time.sleep(0.5)
                            print()
                            print('You kick your enemy and it does 15 damage.')
                            BossHealth = CurrentBossHealth - 15
                            print()
                            return BossHealth

                        if Attack == 'Punch':
                            time.sleep(0.5)
                            print()
                            print(
                                'You punch your enemy and it does 15 damage.')

                            BossHealth = CurrentBossHealth - 15
                            print()
                            return BossHealth

                        if Attack == 'Hall-Douken!':
                            print()
                            time.sleep(0.5)
                            print("You think I care about copyright?!")
                            print()
                            time.sleep(0.5)
                            print("HALL-DOUKEN!")
                            print()
                            time.sleep(0.5)
                            print()
                            print(
                                'You attack with the full force of your SF knowledge and it does 50 damage'
                            )
                            BossHealth = CurrentBossHealth - 50
                            print()
                            return BossHealth

                        if Attack == 'Undertone':
                            print()
                            time.sleep(0.8)
                            print()
                            print("You dig deep...")
                            time.sleep(0.8)
                            print()
                            print("Everything goes dark")
                            time.sleep(0.8)
                            print()
                            print(
                                "You have the underlying feeling of an explosion and..."
                            )
                            time.sleep(1.0)
                            print()
                            print('YOU DEAL 70 POINTS OF DAMAGE')
                            BossHealth = CurrentBossHealth - 70
                            print()
                            return BossHealth
                        if Attack == 'Fast Ball':
                            print()
                            print('Hey catch this for me will ya?')
                            print()
                            time.sleep(0.8)
                            print(
                                "You launch a baseball at 90mph towards your enemy"
                            )
                            print()
                            time.sleep(1.0)
                            print("They don't catch it...")
                            print()
                            time.sleep(1.0)
                            print()
                            print('YOU DEAL 65 POINTS OF DAMAGE')
                            BossHealth = CurrentBossHealth - 65
                            print()
                            return BossHealth

                    except ValueError:
                        time.sleep(0.5)
                        print('Please enter a valid attack')
                    except (ValueError, IndexError):
                        time.sleep(0.5)
                        print('Please enter a valid attack')
                    else:
                        ValidAttack = True
            elif Action == 2:
                Inventory()
        except ValueError:
            time.sleep(0.5)
            print('Please enter a valid action')
        except (ValueError, IndexError):
            time.Sleep(0.5)
            print('Please enter a valid action')
        else:
            ActionTaken = True
import numpy as np
from PIL import ImageGrab
import cv2
import time
import pyautogui
from directKeys import PressKey,W,A,S,D
import os

for i in list(range(4))[::-1]:
    print(i+1)
    time.Sleep(1)

print('down')
PressKey('w')
time.Sleep(3)
print('up')
PressKey('w')


def keys_to_output(keys):
    output = [0,0,0]

    if 'A' in keys:
        output[0] =1
    elif 'D' in keys:
        output[2] =1
    else:
        output[1] = 1
    return output