Ejemplo n.º 1
0
def main():

    global pyglet

    pyglet.lib.load_library('avbin64')
    pyglet.have_avbin = True

    loadSamples()  # load the samples

    track1 = '1k 1k 0s 1k 0k 1k 0s 0s 1k 1k 0s 1k 0k 1k 0s 0k'  #notes in the sequence: first char an int [0,1] -> [False, True] second char [k, s, h, t] -> [kick, snare, hat, tom]
    track2 = '1h 1h 1h 1h 1h 1h 1h 1h 1h 1h 1h 1h 1h 1h 1h 1h'
    track3 = '0s 0s 1s 0s 0s 0s 1s 0s 0s 0s 1s 0s 1s 1s 1s 1s'

    t1 = Thread(target=ch1, args=(track1, 300))  # first track
    t2 = Thread(target=ch1, args=(track2, 300))  # second track
    t3 = Thread(target=ch1, args=(track3, 300))  # third track

    # start all the processes first
    t1.start()
    t2.start()
    t3.start()

    INTERVAL.seconds(5)  # wait to sync

    # join them in order to run them at the same time (supposedly)
    t1.join()
    t2.join()
    t3.join()
Ejemplo n.º 2
0
    def onJoin(self, details):
        self.log.info("Client session joined {details}", details=details)
        i = 5
        # your main app code goes here! eg register procedures, subscribe to topics, etc
        while i < 10:
            #	while True:

            yield led.on()
            print 'on'
            yield pause.seconds(1.5)
            yield led.off()
            print 'off'
            yield pause.seconds(1.0)

            #	humidity, temperature = Adafruit_DHT.read_retry(11, 4)
            #	print i, humidity,temperature
            #	if humidity is not None and temperature is not None:
            #	    print('Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(temperature, humidity))
            #	else:
            #	    print('Failed to get reading. Try again!')
            #	    sys.exit(1)
            #
            #   	x = random.randint(30, 50)

            #	print x
            #	yield self.publish('server.local.cpu', x)
            i = i + 1

#	time.sleep(1)
        self.leave()
Ejemplo n.º 3
0
def main():
    
    print("Started" )   
    loginURL = "https://www.linkedin.com/uas/login"
    
    scrapeOC = "https://www.linkedin.com/search/results/people/?facetGeoRegion=%5B%22pr%3A9349%22%5D&facetIndustry=%5B%2225%22%5D&origin=FACETED_SEARCH"
    
    scrapeUSCA = "https://www.linkedin.com/search/results/people/?facetGeoRegion=%5B%22us%3A0%22%2C%22ca%3A0%22%5D&facetIndustry=%5B%2225%22%5D&origin=FACETED_SEARCH"
    
    scrapePR = ''
    
    with open('un.txt', 'r') as file:
        user = file.read().replace('\n', '')
    
    with open('passw.txt', 'r') as file:
        passw = file.read().replace('\n', '')
    
    
    driver = webdriver.Firefox()
    
    logIn(driver, loginURL, user, passw)
    
    pos.seconds(3)
    
    #scrape todos los paises excepto canada y US
    scrape(driver, scrapeOC, "_otherCountries.csv")
Ejemplo n.º 4
0
def record_AN_port(fname):
    """
    Start recording data from Axis Neuron port at some predetermined time and saves it to file name.
    
    Params:
    -------
    fname (str)
    """
    while not os.path.isfile(
            'C:/Users/Eddie/Dropbox/Sync_trials/Data/start.txt'):
        pause.seconds(1)

    data = []  # Port output.
    portOut = [datetime.now()] * 2
    startTime = datetime.now()
    max_wait_time = 1000
    while (
        (not os.path.isfile('C:/Users/Eddie/Dropbox/Sync_trials/Data/end.txt'))
            and (datetime.now() - startTime).total_seconds() < max_wait_time):
        portOut = read_port()
        data.append(portOut)

    headers = list(calc_file_headers())
    headers[-1] = ''.join(
        headers[-1].split())  # Remove space in last column header.
    with open(fname, 'w') as f:
        f.write('Start time: %s\n' % data[0][0].isoformat())
        f.write('End time: %s\n\n' % data[-1][0].isoformat())
        f.write('Timestamp ' + ' '.join(headers) + '\n')
        for d in data:
            t = d[0].isoformat()
            #if '\r' in d[1] or '\n' in d[1]:
            #    raise Exception
            f.write('%s %s\n' % (t, d[1].rstrip()))
Ejemplo n.º 5
0
    def auto_ping(self):
        while True:
            try:
                self.ping()
            except:
                pass

            pause.seconds(5)
Ejemplo n.º 6
0
def initialize():
    print("Proceeding with EnviroPlus\'s warm up...")
    for x in range(10):
        print("Cycle {} out of 10".format(str(x + 1)))
        bme280.get_temperature()
        bme280.get_pressure()
        bme280.get_humidity()
        ltr559.get_lux()
        pause.seconds(1)
    print("Enviro is now warmed up and ready!")
Ejemplo n.º 7
0
    def _run(self):
        """ the actual run """
        services = []
        try:
            services = self.get_services()
        except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError):
            log.error('Cannot connect to docker')

        for service in services:
            webhook = Webhooks(service)
            try:
                service_name = service.name
                image_with_digest = service.attrs['Spec']['TaskTemplate']['ContainerSpec']['Image']
                image, image_sha = self.__get_image_parts(image_with_digest)
                prometheus.PROM_SVC_UPDATE_COUNTER.labels(service_name, service.id, service.short_id, image).inc(0)
                update_image = self.__get_updated_image(image_sha=image_sha, image=image)
                service_updated = False
                if update_image:
                    service_updated = self.__update_image(service, update_image)

                if service_updated:
                    webhook.trigger()
                    updating = True
                    while updating:
                        service.reload()
                        service_updated = True

                        if (
                                service.attrs.get('UpdateStatus')
                                and service.attrs['UpdateStatus'].get('State') == 'updating'
                        ):
                            log.debug(f'Service {service_name} is in status `updating`. Waiting 1s...')
                            pause.seconds(1)
                        else:
                            log.debug(f'Service {service_name} has converged.')
                            updating = False

                if service_updated:
                    prometheus.PROM_SVC_UPDATE_COUNTER.labels(service_name, service.id, service.short_id, image).inc(1)
                    notify = {
                        'service_name': service_name,
                        'service_short_id': service.short_id,
                    }
                    if self.settings['notify_include_image']:
                        notify['image'] = image
                    if self.settings['notify_include_old_image']:
                        notify['old_image'] = image_with_digest
                    if self.settings['notify_include_new_image']:
                        notify['new_image'] = service.attrs['Spec']['TaskTemplate']['ContainerSpec']['Image']
                    self.notify(**notify)
            except docker.errors.NotFound as error:
                log.debug(f'Exception caught: {error}')
                log.warning(f'Service {service_name} disappeared. Reloading the service list.')
                services = self.get_services()
Ejemplo n.º 8
0
    def test_time(self):
        """ test_time
        Test 5 second delay
        """
        now = time.time()
        pause.seconds(5)
        end = time.time()

        # True if 5 seconds have passed
        diff = int(end - now)
        self.assertEqual(diff, 5)
Ejemplo n.º 9
0
def main():
    welcomeMessage()

    while True:
        print('')
        playerChoice = playerChoose().capitalize()
        displayPlayerChoice(playerChoice)
        pause.seconds(1)
        aiChoice = aiChoose()
        outcome = checkWinner(playerChoice, aiChoice)

        print(outcomeMessage(outcome))
        pause.seconds(1)
        input('Play Again?')
Ejemplo n.º 10
0
    def test_past(self):
        """ test_past
        Test a time that has already passed
        """

        # Using seconds()
        start = time.time()
        pause.seconds(-5)
        end = time.time()
        self.assertEqual(int(end - start), 0)

        # Using until()
        start = time.time()
        pause.until(time.time() - 10)
        end = time.time()
        self.assertEqual(int(end - start), 0)
Ejemplo n.º 11
0
    def connect(self):
        global_value.check_websocket_if_connect = None

        self.websocket_client = WebsocketClient(self)

        self.websocket_thread = threading.Thread(
            target=self.websocket.run_forever,
            kwargs={
                'sslopt': {
                    "check_hostname": False,
                    "cert_reqs": ssl.CERT_NONE,
                    "ca_certs": "cacert.pem"
                },
                "ping_interval": 5
            }
        )  # for fix pyinstall error: cafile, capath and cadata cannot be all omitted
        self.websocket_thread.daemon = True
        self.websocket_thread.start()

        while True:
            try:
                if global_value.check_websocket_if_connect == 0 or global_value.check_websocket_if_connect == -1:
                    return False
                elif global_value.check_websocket_if_connect == 1:
                    break
            except Exception:
                pass

            pass

        if self.token:
            self.authorize(authorize=self.token)

        start_t = time.time()
        while self.profile.msg is None:
            if time.time() - start_t >= 30:
                logging.error('**error** authorize late 30 sec')
                return False

            pause.seconds(0.01)

        return True
Ejemplo n.º 12
0
def main():

    print("Started")
    loginURL = "https://www.linkedin.com/uas/login"

    scrapeOC = "https://www.linkedin.com/search/results/people/?facetGeoRegion=%5B%22cb%3A0%22%2C%22cr%3A0%22%2C%22do%3A0%22%2C%22gt%3A0%22%2C%22mx%3A0%22%2C%22ni%3A0%22%2C%22pa%3A0%22%2C%22pr%3A9349%22%5D&facetIndustry=%5B%2225%22%5D&origin=FACETED_SEARCH"

    scrapeUSCA = "https://www.linkedin.com/search/results/people/?facetGeoRegion=%5B%22us%3A0%22%2C%22ca%3A0%22%5D&facetIndustry=%5B%2225%22%5D&origin=FACETED_SEARCH"

    user = '******'
    passw = 'password here'

    driver = webdriver.Firefox()

    logIn(driver, loginURL, user, passw)

    pos.seconds(3)

    #scrape todos los paises excepto canada y US
    scrape(driver, scrapeOC)
Ejemplo n.º 13
0
        def open_sites():
            try:
                driver.get('https://bobrtc.tel/')
                radio_passed = True
            except NameError:
                msg = QMessageBox()
                msg.setText("No Browser Has Been Selected.")
                msg.setStyleSheet("QLabel{ color: black}")
                msg.setWindowTitle("Error")
                msg.setIcon(QMessageBox.Critical)
                msg.exec_()
                radio_pressed = False

            right_page = 'BobRTC' in driver.title

            if right_page == False:
                print('Error')
            else:
                print('WebPage Loaded Successfully')

            try:
                driver.find_element_by_id('loginButton')
            except selenium.common.exceptions.NoSuchElementException:
                pass

            while True:
                current_url = driver.current_url

                if 'bobrtc.live' in current_url:
                    break
                else:
                    pass

            for i in range(int(call_amount)):
                driver.execute_script(f"window.open('{bob_url}');")
                pause.seconds(int(time))
Ejemplo n.º 14
0
def logIn(driver, loginURL, X, Z):

    driver.get(loginURL)

    uin = driver.find_element_by_xpath('//*[@id="username"]')
    uin.clear()
    pos.seconds(1)
    uin.send_keys(X)

    passkey = driver.find_element_by_xpath('//*[@id="password"]')
    passkey.clear()
    pos.seconds(1)
    passkey.send_keys(Z)
    pos.seconds(1)
    passkey.send_keys(Keys.RETURN)

    pos.seconds(3)
Ejemplo n.º 15
0
    ltr559 = LTR559()
except ImportError:
    import ltr559
from bme280 import BME280
import sqlite3
from sqlite3 import Error
import time
from sklearn.linear_model import LinearRegression
import numpy as np

# BME280 temperature/pressure/humidity sensor
bme280 = BME280()

# PMS5003 particulate sensor
pms5003 = PMS5003()
pause.seconds(1)

sql_table_scheme = """ CREATE TABLE IF NOT EXISTS readings (
                            timestamp numeric NOT NULL,
                            remotetemperature real NOT NULL,
                            remotehumidity real NOT NULL,
                            temperature real NOT NULL,
                            humidity real NOT NULL,
                            pressure real NOT NULL,
                            light real NOT NULL,
                            cputemperature real NOT NULL
                        );"""

parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument("--device", "-d", help="Set the device MAC-Address in format AA:BB:CC:DD:EE:FF",
                    metavar="AA:BB:CC:DD:EE:FF")
Ejemplo n.º 16
0
def start_capture(PHASE=NAUTICAL):
	# Make a note in the log that we're starting a new run:
	logdiv("=")
	logmsg("Starting new image run at: " + str_local(datetime.now()))	

	# Declare global variables
	global WAIT_BETWEEN, EXPOSURE_TIME, GAIN, GAMMA, LATITUDE, LONGITUDE, CAMERA, USE_PUSHOVER

	# Define a few key variables
	[ START_TIME, END_TIME ] = sunpos.twilight_time(PHASE, LATITUDE, LONGITUDE, datetime.utcnow())		# When to start and finish taking images
	
	while START_TIME is None:									# If sun is always up, fallback one twilight phase
		logmsg("Selected twilight phase does not occur for this location / date.  Falling back to earlier twilight.")
		PHASE = PHASE - 1
		if PHASE < 0:
			logdiv('*')
			logmsg('ERROR: sun always above horizon - cannot set start time.  Exiting')
			logdiv('*')
			raise RuntimeError('Error: sun always above horizon - cannot set start time.')
		[ START_TIME, END_TIME ] = sunpos.twilight_time(PHASE, LATITUDE, LONGITUDE, datetime.utcnow())
	
	duration = END_TIME - START_TIME
	duration_hours = duration.seconds // 3600
	duration_minutes = duration.seconds // 60 % 60

	# WAIT_BETWEEN = 0.1											# Seconds to wait between images
	# EXPOSURE_TIME = 30											# Exposure time in seconds
	# GAIN = 200													# Camera gain setting
	# GAMMA = 50													# Image gamma

	TONIGHT = START_TIME.strftime("%Y%m%d")						# Tonight's date
	NIGHTDIR = BASEDIR + TONIGHT + "/"							# Base directory for images 
	if not os.path.exists(NIGHTDIR):							# Make sure the directory exists, otherwise create it
		os.makedirs(NIGHTDIR)
	LOGFILE = NIGHTDIR + "capture_log_" + TONIGHT + ".log"		# Set up the logging for tonight

	logmsg("Capturing images to folder: " + NIGHTDIR)
	
	# Initialize the camera:
	if CAMERA is None:
		CAMERA = skycam.initialize()
	skycam.set_controls(GAIN, GAMMA)

	# Wait until start of twilight and then start capturing images:
	logdiv("-",LOGFILE)
	logmsg("Exposure = " + str(EXPOSURE_TIME) + " | Gain = " + str(GAIN) + " | Gamma = " + str(GAMMA), LOGFILE)
	logmsg("Current time is     :  " + str_local(datetime.now()), LOGFILE)
	logmsg("Waiting until       :  " + str_local(START_TIME), LOGFILE)
	logmsg("Imaging will end at :  " + str_local(END_TIME), LOGFILE)
	logmsg("Total Duration is   :  " + str(duration_hours) + " hours " + str(duration_minutes) + " minutes", LOGFILE)
	logdiv("-",LOGFILE)

	if USE_PUSHOVER:
		title = "Ready For Next Sequence"
		message = "SkyCam is online and will begin capture at " + START_TIME.strftime("%H:%M %d-%b-%Y")
		sendPushoverAlert(title, message)

	pause.until(START_TIME)						
	
	if USE_PUSHOVER:
		title = "Starting Image Acquisition"
		message = "SkyCam is capturing images.\n\nImage capture will finish at " + END_TIME.strftime("%H:%M %d-%b-%Y")
		sendPushoverAlert(title, message)
	
	while datetime.now() < END_TIME:
		now = datetime.now()
		filename = name_local(now) + FILE_EXT
		skycam.capture(long(EXPOSURE_TIME * 1e6), NIGHTDIR + filename) 
		logmsg("Captured image: " + filename, LOGFILE)
		pause.seconds(WAIT_BETWEEN)

	logmsg("Finished capturing images", LOGFILE)
	logdiv("-",LOGFILE)
	LOGFILE = None

	data = OrderedDict( [
		   	( "start", START_TIME ),
			( "finish", END_TIME ),
			( "exposure", EXPOSURE_TIME),
			( "gain", GAIN ),
			( "gamma", GAMMA ),
			( "interval", WAIT_BETWEEN ),
			( "latitude", LATITUDE ),
			( "longitude", LONGITUDE ),
			( "create_timelapse", CREATE_TIMELAPSE),
			( "create_startrails", CREATE_STARTRAILS),
			( "upload_server", REMOTE_SERVER),
			( "upload_path", REMOTE_PATH),
			( "remote_command", REMOTE_COMMAND),
			( "clean_up_folders", CLEAN_UP),
			( "days_to_keep", DAYS_TO_KEEP)  ],)
	store_data(data, "capture_settings.json", NIGHTDIR)

	return NIGHTDIR
Ejemplo n.º 17
0
                    results_list[7] = ', '.join(results_list[7:9])
                    results_list.pop(8)
                    results_list.pop(-1)
                    title = results_list[0].split(' ')
                    profession = results_list[1].split(' ')
                    professional = Convert(results_list[2:])
                    professional['Prefix'] = title[0]
                    professional['Last_name'] = title[-1]
                    professional['Given_name'] = ' '.join(title[1:-1])
                    professional['Profession'] = profession[1]
                    sub_list.append(professional)
                    stop = time.time()
                    print('finished in {}s \n'.format(stop - start))
                    # print('pause {0}'.format(time.ctime()))
                    # print('pause down {0}'.format(time.ctime()))
                except IndexError:
                    pass
                time_space_rand = randint(5, 10, 1)[0]
                #print('Auto pausing of {}s is randomly chosen-----\n'.format(time_space_rand))
                pause.seconds(time_space_rand)
                d = pd.DataFrame(sub_list)
                empty_df = empty_df.append(d)
                concat_list.append(sub_list)
            chunk_concat = chunk_concat.append(empty_df)
            chunk_concat_new = chunk_concat.drop_duplicates()
            file_name = 'go_' + '1' + '.csv'
            chunk_concat_new.to_csv(file_name)
            print('chunk.csv dumped')
            #print('auto pausing triggered again-------\n')
            pause.seconds(randint(7, 10, 1)[0])
Ejemplo n.º 18
0
    def sendCalls(self):
        bob_url = self.lineEdit.text()
        time = self.lineEdit_2.text()
        call_amount = self.lineEdit_3.text()
        refresh = self.lineEdit_4.text()
        use_chrome = self.radioButton.isChecked()
        use_firefox = self.radioButton_2.isChecked()

        windows_user = os.getlogin()

        if use_chrome == True:
            options = webdriver.ChromeOptions()
            options.add_argument(
                f"user-data-dir=C:\\Users\\{windows_user}\\AppData\\Local\\Google\\Chrome\\User Data\\Default"
            )
            driver = webdriver.Chrome(options=options)
        elif use_firefox == True:
            driver = webdriver.Firefox()

        kb = Controller()

        def open_sites():
            try:
                driver.get('https://bobrtc.tel/')
                radio_passed = True
            except NameError:
                msg = QMessageBox()
                msg.setText("No Browser Has Been Selected.")
                msg.setStyleSheet("QLabel{ color: black}")
                msg.setWindowTitle("Error")
                msg.setIcon(QMessageBox.Critical)
                msg.exec_()
                radio_pressed = False

            right_page = 'BobRTC' in driver.title

            if right_page == False:
                print('Error')
            else:
                print('WebPage Loaded Successfully')

            try:
                driver.find_element_by_id('loginButton')
            except selenium.common.exceptions.NoSuchElementException:
                pass

            while True:
                current_url = driver.current_url

                if 'bobrtc.live' in current_url:
                    break
                else:
                    pass

            for i in range(int(call_amount)):
                driver.execute_script(f"window.open('{bob_url}');")
                pause.seconds(int(time))

        while True:
            open_sites()
            pause.seconds(int(refresh))

            while len(driver.window_handles) > 1:
                kb.press(Key.ctrl)
                kb.press('w')
                kb.release('w')
                kb.release(Key.ctrl)
                pause.seconds(0.15)
Ejemplo n.º 19
0
def py_waitForNextBlock(web3_obj, wait_msg):
    block_num_prev = web3_obj.eth.blockNumber
    while web3_obj.eth.blockNumber <= block_num_prev:
        pause.seconds(1)
        print(wait_msg)
Ejemplo n.º 20
0
try:
    #Path to firefox profile. For using installed addons (like adblock)
    fp = webdriver.FirefoxProfile("/Users/Mik/Documents/fx_profile")
    driver = webdriver.Firefox(firefox_profile=fp)
except IOError:
    driver = webdriver.Firefox()
except:
    driver = webdriver.Chrome()


#COLLECT VIDEOS
link_file = os.path.dirname(sys.argv[0]) + '/links.txt' #working correctly with pyinstaller
for line in open(link_file, "rb"):
    driver.get(line.rstrip())
    pause.seconds(1)

    #get links of videos
    select = driver.find_elements_by_xpath('//a[@class="yt-uix-sessionlink yt-uix-tile-link  spf-link  yt-ui-ellipsis yt-ui-ellipsis-2"]')
    #duration of videos
    select2 = driver.find_elements_by_xpath('//span[@class="video-time"]')
    select3 = iter(select2)
    
    for i in select:
        title = i.get_attribute('innerText')#get title of link
        video_link = i.get_attribute('href')#get link video
        time = select3.next().get_attribute('innerText')#get duration video
        #Info about duration add to link in list
        links.insert(counter,video_link+' '+time) #using INSERT for mixing videos
        
        counter += 2 #counter for mixing video from other 
Ejemplo n.º 21
0
    def connect(self):
        global_value.check_websocket_if_connect = None

        self.websocket_client = WebsocketClient(self)

        self.websocket_thread = threading.Thread(
            target=self.websocket.run_forever,
            kwargs={
                'sslopt': {
                    "check_hostname": False,
                    "cert_reqs": ssl.CERT_NONE,
                    "ca_certs": "cacert.pem"
                },
                "ping_interval": 0,
                'skip_utf8_validation': True,
                "origin": "https://app.expertoption.com",
                # "http_proxy_host": '127.0.0.1', "http_proxy_port": 8890
            })

        self.websocket_thread.daemon = True
        self.websocket_thread.start()

        while True:
            try:
                if global_value.check_websocket_if_connect == 0 or global_value.check_websocket_if_connect == -1:
                    return False
                elif global_value.check_websocket_if_connect == 1:
                    break
            except Exception:
                pass
            pass

        # self.authorize(authorize=self.token)

        # TODO support it
        # self.multiple_action(actions=[
        #     self.get_countries(json=True),
        #     self.get_currency(json=True),
        #     self.get_profile(json=True),
        #     self.get_environment(json=True),
        #     self.get_open_options(json=True),
        #     self.get_user_group(json=True),
        #     self.get_set_time_zone(json=True),
        #     self.get_history_steps(json=True),
        #     self.get_trade_history(json=True),
        # ], ns="_common")

        self.send_websocket_request(action="multipleAction",
                                    msg={
                                        "token": self.token,
                                        "v": 18,
                                        "action": "multipleAction",
                                        "message": {
                                            "token":
                                            self.token,
                                            "actions": [{
                                                "action": "getCountries",
                                                "message": None,
                                                "ns": None,
                                                "v": 18,
                                                "token": self.token
                                            }, {
                                                "action": "getCurrency",
                                                "message": None,
                                                "ns": None,
                                                "v": 18,
                                                "token": self.token
                                            }, {
                                                "action": "profile",
                                                "message": None,
                                                "ns": None,
                                                "v": 18,
                                                "token": self.token
                                            }, {
                                                "action": "environment",
                                                "message": None,
                                                "ns": None,
                                                "v": 18,
                                                "token": self.token
                                            }, {
                                                "action": "assets",
                                                "message": {
                                                    "mode":
                                                    ["vanilla", "binary"],
                                                    "subscribeMode":
                                                    ["vanilla"]
                                                },
                                                "ns": None,
                                                "v": 18,
                                                "token": self.token
                                            }, {
                                                "action": "openOptions",
                                                "message": None,
                                                "ns": None,
                                                "v": 18,
                                                "token": self.token
                                            }, {
                                                "action": "userGroup",
                                                "message": None,
                                                "ns": None,
                                                "v": 18,
                                                "token": self.token
                                            }, {
                                                "action": "setTimeZone",
                                                "message": {
                                                    "timeZone": 360
                                                },
                                                "ns": None,
                                                "v": 18,
                                                "token": self.token
                                            }, {
                                                "action": "historySteps",
                                                "message": None,
                                                "ns": None,
                                                "v": 18,
                                                "token": self.token
                                            }, {
                                                "action": "tradeHistory",
                                                "message": {
                                                    "mode":
                                                    ["binary", "vanilla"],
                                                    "count": 100,
                                                    "index_from": 0
                                                },
                                                "ns": None,
                                                "v": 18,
                                                "token": self.token
                                            }]
                                        }
                                    },
                                    ns="_common")

        self.ping_thread = threading.Thread(target=self.auto_ping)
        self.ping_thread.daemon = True
        self.ping_thread.start()

        start_t = time.time()
        while self.profile.msg is None:
            if time.time() - start_t >= 30:
                logging.error('**error** profile late 30 sec')
                return False

            pause.seconds(0.01)

        return True
Ejemplo n.º 22
0
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from bs4 import BeautifulSoup

options = webdriver.ChromeOptions()
# options.add_argument("--ignore-certificate-errors")
options.add_argument("--incognito")
# options.add_argument("--kiosk")

driver = webdriver.Chrome(options=options, executable_path=r'/Users/jbaripatti/Development/chromedriver')

PAGE = 'https://www.sephora.com/ca/en/shop/foundation-makeup'

driver.get(PAGE)
pause.seconds(1)

# close pop-up
icon_cross_ele = driver.find_element_by_css_selector('svg.css-1bpyffv').click()
pause.seconds(2)

# select view all items
icon_select_all = Select(driver.find_element_by_css_selector("select.css-bpk111"))
icon_select_all.select_by_value('300')
pause.seconds(5)

# driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

# Wait 30 seconds for page to load and extract the element after it loads
timeout = 30
try:
Ejemplo n.º 23
0
               if not delay_checked:
                  delay_checked = True
                  answer = input("do you want to check for delay? ")
                  if (answer == "yes"):
                      start_delay = nhl.game_start_delay(team_id,today)
                      answer = input("delay is of {0}, do you want to update current delay ({1})? ".format(start_delay,delay))
                      if (answer == "yes"):
                          delay = input("Enter new delay : ")
               # check game
               # Check score online and save score
               new_score = nhl.fetch_score(team_id)
                # If score change...
               if new_score != old_score:
                   if new_score > old_score:
                       pause.seconds(delay)
                       # save new score
                       print("GOAL!")
                       # activate_goal_light()
                       light.activate_goal_light()
                   old_score = new_score

           elif ('Final' in game_status):
               light.cleanup()
               print ("Game ended, cleanning up!")
               break

           else:
               old_score = 100 # Reset for new game
               next_game_date = nhl.get_next_game_date(team_id)
               print ("Going to sleep until start of next game : " + str(next_game_date))
 def run(self):
     for i in range(5):
         print("mahesh")
         pause.seconds(1)
Ejemplo n.º 25
0
def main():
    try:
        os.system('porcupine_demo_mic --keywords blueberry')
        playsound('C:\\Users\\ADMIN\\Desktop\\VIRTUAL ASSISTANT\\chime.wav')
        voice_data = takecommand().lower()
        if 'beatbox' in voice_data or 'bit box' in voice_data or 'big box' in voice_data or 'bigbox' in voice_data:
            playsound(
                'C:\\Users\\ADMIN\\Desktop\\VIRTUAL ASSISTANT\\preview.mp3')
        if 'repeat' in voice_data:
            voice_data = voice_data.replace("repeat", "")
            voice_data = voice_data.replace("that", "")
            speak(voice_data)

        if ('time') in voice_data:
            strTime = datetime.datetime.now().strftime("%I:%M:%S")
            timemsg = (f', {strTime}'), (f'it is , {strTime}'), (
                f'the current time is, {strTime}'), (f'its , {strTime}')
            speak(random.choice(timemsg))

        elif ('date' in voice_data):
            date()

        elif 'i am sad' in voice_data:
            smg = 'here is something for you ' + jokes(
            ), 'i hate that one', 'i, really dont like it'
            speak(random.choice(smg))

        elif 'i am happy' in voice_data:
            msg = 'Life is full of happiness and tears; be strong and have faith.', 'On a deeper level you are already complete. When you realize that, there is a playful, joyous energy behind what you do', 'Most people are about as happy as they make up their minds to be', 'i am also happy'
            speak(random.choice(msg))

        elif 'i love you' in voice_data:
            reply = 'i also like you', 'i like it', "i don't hate you", 'i also love you as a friend'
            speak(random.choices(reply))

        elif ("tell me about yourself" in voice_data):
            personal()
        elif ("about you" in voice_data):
            personal()

        elif ("who are you" in voice_data):
            personal()

        elif ("yourself" in voice_data):
            personal()

        elif 'tell me the weather in' in voice_data or "tell me today's weather in" in voice_data:
            voice_data = voice_data.replace("weather", "")
            voice_data = voice_data.replace("of", "")
            voice_data = voice_data.replace("at", "")
            voice_data = voice_data.replace("the", "")
            voice_data = voice_data.replace("in", "")
            voice_data = voice_data.replace("city", "")
            voice_data = voice_data.replace("tell", "")
            voice_data = voice_data.replace("me", "")
            voice_data = voice_data.replace("can", "")
            voice_data = voice_data.replace("you", "")
            voice_data = voice_data.replace("today's", "")
            voice_data = voice_data.replace("in", "")

            api_key = "30b2e680ad9c7790ec02fdb4f97f4573"
            base_url = "http://api.openweathermap.org/data/2.5/weather?"
            city_name = voice_data
            complete_url = base_url + "appid=" + api_key + "&q=" + city_name
            response = requests.get(complete_url)
            x = response.json()
            if x["cod"] != "404":
                y = x["main"]
                current_temperature = y["temp"]
                current_pressure = y["pressure"]
                current_humidiy = y["humidity"]
                z = x["weather"]
                weather_description = z[0]["description"]
                r = ("in " + city_name + " Temperature is " +
                     str(int(current_temperature - 273.15)) +
                     " degree celsius " + ", atmospheric pressure " +
                     str(current_pressure) + " hpa unit" + ", humidity is " +
                     str(current_humidiy) + " percent"
                     " and " + str(weather_description))
                speak(r)

            else:
                speak(" City Not Found ")

        elif 'tell me the weather' in voice_data:
            weather()

        elif 'youtube' in voice_data:
            voice_data = voice_data.replace("youtube", "")
            voice_data = voice_data.replace("search", "")
            voice_data = voice_data.replace("on", "")
            voice_data = voice_data.replace("youtube", "")
            site = 'https://youtube.com/search?q=' + voice_data
            webbrowser.open(site)
        elif 'tell me the temperature' in voice_data:
            weather()

        elif "tell me today's weather" in voice_data:
            weather()

        elif "tell me today's temperature" in voice_data:
            weather()

        if 'wikipedia' in voice_data:
            speak('Searching Wikipedia...')
            voice_data = voice_data.replace("wikipedia", "")
            results = wikipedia.summary(voice_data, sentences=2)
            speak("According to Wikipedia")
            print(results)
            speak(results)

        elif 'clock' in voice_data:
            path = 'F:\\digitalClock.py'
            os.startfile(path)

        elif "open website" in voice_data:
            speak("Tell me the name of the website")
            search = takecommand().lower()
            speak('Opening' + search)
            url = 'www.' + search + '.com'
            webbrowser.open(url)

        elif ("song" in voice_data or 'music' in voice_data
              or 'gana' in voice_data):
            speak("playing a random song")
            path = 'D:\\music\\'
            files = os.listdir(path)
            d = random.choice(files)
            os.startfile('D:\\music\\' + d)

        elif 'clear reminders' in voice_data or 'clear all reminder' in voice_data:
            replyt = 'ok clearing all the reminders ', 'cleared', 'cleared all the reminders'
            speak(random.choice(replyt))
            f = open("data.txt", "r+")
            f.seek(0)
            f.truncate()

        elif ("create a reminder list" in voice_data
              or "set a reminder" in voice_data):
            speak("What is the reminder?")
            data = takecommand()
            speak("You said to remember that" + data)
            reminder_file = open("data.txt", 'a')
            reminder_file.write('\n')
            reminder_file.write(data)
            reminder_file.close()

        elif 'full form of friday' in voice_data:
            speak('Female Replacement Intelligent Digital Assistant Youth')

        elif 'face' in voice_data:
            speak('opening face recognition')
            path = 'F:\\detect_face_video.py'
            os.startfile(path)

        elif ("do you know anything" in voice_data
              or "remember" in voice_data):
            reminder_file = open("data.txt", 'r')
            speak("You said me to remember that: " + reminder_file.read())

        elif ("powers" in voice_data or "help" in voice_data
              or "features" in voice_data or 'what can you do' in voice_data):
            features = ''' i can help to do lot many things like..
                i can tell you the current time and date,
                i can tell you the current weather,
                i can tell you battery and cpu usage,
                i can create the reminder list,
                i can shut down or logout or hibernate your system,
                i can tell you non funny jokes,
                i can open any website,
                i can repeat what you  you told me,
                i can search the thing on wikipedia,
                i can change my voice from male to female and vice-versa
                i have  a search engine make by my boss if you want to know something just say open search and ask the question
                i have a wake word detection i will be online if you say hey mark
                And yes one more thing, My boss is working on this system to add more features...,
                tell me what can i do for you??
                '''
            speak(features)

        elif ("voice" in voice_data):
            if 'female' in voice_data:
                femalevoice()

            else:
                malevoice()

        elif ('i am done' in voice_data or 'bye bye mark' in voice_data
              or 'go offline mark' in voice_data or 'bye' in voice_data):
            sys.exit()

        elif ("how's your day going" in voice_data
              or 'how is your day going' in voice_data):
            speak('Wonderfull , thanks for asking me, how can i help you ')

        elif 'change name' in voice_data:
            f = open("C:\\Users\\ADMIN\\Desktop\\VIRTUAL ASSISTANT\\name.txt",
                     "r+")
            f.seek(0)
            f.truncate()
            speak('tell me your name')
            sname = takecommand()()
            try:
                if 'neelam' in sname:
                    file1 = open(
                        "C:\\Users\\ADMIN\\Desktop\\VIRTUAL ASSISTANT\\name.txt",
                        "w")
                    file1.write(sname)
                    file1.close()
                    file_contents = f.read()
                    speak('from now i will call you sir' + file_contents)

            except Exception as e:
                file1 = open(
                    "C:\\Users\\ADMIN\\Desktop\\VIRTUAL ASSISTANT\\name.txt",
                    "w")
                file1.write(sname)
                file1.close()
                file_contents = f.read()
                speak('from now i will call you sir' + file_contents)

        elif 'change birthday' in voice_data:
            f = open("C:\\MARK\\birthday.txt", "r+")
            f.seek(0)
            f.truncate()
            speak('tell me the birthday date')
            sname = takecommand()()
            file1 = open("C:\\MARK\\birthday.txt", "w")
            file1.write(sname)
            file1.close()
            file_contents = f.read()
            speak('so your birthday is at' + file_contents)

        elif 'my birthday' in voice_data:
            f = open('C:\\MARK\\birthday.txt', 'r')
            file_contents = f.read()
            speak(file_contents)

        elif 'hey there' in voice_data:
            speak('hello there')

        elif 'tell me my name' in voice_data:
            f = open('C:\\Users\\ADMIN\\Desktop\\VIRTUAL ASSISTANT\\name.txt',
                     'r')
            file_contents = f.read()
            speak(file_contents)

        elif 'what is my name' in voice_data:
            f = open('C:\\MARK\\my name.txt', 'r')
            file_contents = f.read()
            speak(file_contents)

        elif 'shutdown' in voice_data or 'turn off' in voice_data or '':
            speak('system offline')
            os.system("shutdown /p")

        elif 'open instagram' in voice_data:
            speak('opening Instagram')
            webbrowser.open('https://www.instagram.com/?hl=en')

        elif 'full form of jarvis' in voice_data:
            speak('Just A Rather Very Intelligent System')

        elif 'news' in voice_data:
            speak('here you go sir')
            path = 'C:\\Users\\ADMIN\\Desktop\\VIRTUAL ASSISTANT\\news.py'
            os.startfile(path)

        elif 'screenshot' in voice_data:
            speak('ok sir')
            screenshot()

        elif 'cpu' in voice_data:
            cpu()

        elif ('there' in voice_data or 'dear' in voice_data):
            speak('For you Sir always')

        elif 'battery' in voice_data:
            battery()

        elif 'joke' in voice_data:
            jokes()

        elif 'open location' in voice_data:
            speak('tell me the location you are looking for')
            location = takecommand()()
            url2 = 'https://google.nl/maps/place/' + location + '/&amp;'
            webbrowser.open(url2)
            speak('location on your screen boss')

        elif 'close browser' in voice_data:
            try:
                speak('as you wish')
                os.system('TASKKILL /F /IM msedge.exe')

            except Exception as e:
                speak("i cant do that right now")

        elif 'close all' in voice_data:
            try:
                speak('as you wish')
                os.system('TASKKILL /F /IM *')

            except Exception as e:
                speak("i cant do that right now")
        elif 'close file' in voice_data:
            try:
                speak('as you wish')
                os.system('TASKKILL /F /IM Explorer.exe')

            except Exception as e:
                speak("i cant do that right now")

        elif 'my location' in voice_data:
            speak('opening your home location on browser')
            loc = 'https://www.google.co.in/maps/@26.1317482,91.8018681,18.5z'
            webbrowser.open(loc)

        elif 'google' in voice_data:
            voice_data = voice_data.replace("google", "")
            voice_data = voice_data.replace("it", "")
            speak('here you go ')
            url69 = 'https://google.com/search?q=' + voice_data
            webbrowser.open(url69)

        elif 'switch window' in voice_data:
            pyautogui.keyDown("alt")
            pyautogui.press("tab")
            pyautogui.press("right")
            pyautogui.keyUp("alt")
            speak('window switched')

        elif 'close' in voice_data:
            pyautogui.keyDown("alt")
            pyautogui.press("F4")
            pyautogui.keyUp()
            speak('application killed')

        elif 'what is your name' in voice_data:
            speak('MY NAME is Mark')

        elif 'whatsapp' in voice_data:
            speak('opening whatsapp')
            wpath = 'C:\\Users\\admin\\AppData\\Local\\WhatsApp\\WhatsApp.exe'
            os.startfile(wpath)

        elif 'wish birthday' in voice_data:
            speak('this is for you')
            path = 'D:\\project Friday\\Y2Mate (mp3cut.net) (1).mp3'
            os.startfile(path)

        elif 'tell me my birthday' in voice_data:
            speak('i remember that you told me your birthday is at 20th march')

        elif 'folder' in voice_data:
            speak('tell me the name of the folder')
            path = 'C:\\Users\\ADMIN\\Desktop'
            os.chdir(path)
            Newfolder = takecommand()()
            os.makedirs(Newfolder)
            speak('i have  made a folder named' + Newfolder +
                  'in you dekstop directry')

        elif 'hello mark' in voice_data or 'lo mark' in voice_data:
            speak("hello sir how's going")

        elif 'hey  mark' in voice_data:
            speak('hey sir what can i do for you')

        elif 'editor' in voice_data or 'visual studio code' in voice_data:
            speak('opening code editor')
            os.startfile(
                'C:\\Users\\ADMIN\\AppData\\Local\\Programs\\Microsoft VS Code\\code.exe'
            )

        elif 'cmd' in voice_data or 'command' in voice_data:
            os.startfile('cmd.exe')

        elif 'red or blue' in voice_data:
            speak('BLue sir')

        elif 'your favorite colour' in voice_data or 'tell me your favourite colour' in voice_data:
            speak('blue')

        elif 'change colour' in voice_data:
            os.system('color 03')

        elif 'how are you' in voice_data:
            msg = "i'm well how are you?", "i'm good", " nice , how's your day going", 'Wonderfull', 'excellent', 'great,thanks for asking'
            speak(random.choice(msg))

        elif 'ip address' in voice_data:
            ip = get('https://api.ipify.org').text
            speak(f'your ip address is {ip}"')

        elif 'hello' in voice_data:
            speak('hello boss')

        if 'restart' in voice_data:
            os.startfile(
                "C:\\Users\\ADMIN\\Desktop\\VIRTUAL ASSISTANT\\ASSISTANT.py")

        if 'amazon order' in voice_data:
            url = 'https://www.amazon.in/gp/css/order-history?ref_=nav_orders_first'
            webbrowser.open(url)
            sys.exit

        if 'wake up' in voice_data:
            speak('Online and ready boss')

        if "you can't do anything" in voice_data or 'you are nothing' in voice_data or 'you are dumb' in voice_data or 'you dont have brain' in voice_data or 'you are mad' in voice_data:
            speak("Sorry boss")

        elif 'wake word' in voice_data:
            speak('my wake word is : hey mark')

        elif 'sleep' in voice_data:
            speak(
                'As you wish, for now i will sleep if you want me you can call me '
            )

        elif 'boreing' in voice_data:
            speak('lets play some music')
        elif 'email' in voice_data:
            speak('are you the sender?')
            sender = takecommand()()

            if 'yes' in sender:
                try:
                    speak("Please Enter Email address of Recipient.")
                    Recipient_user = takecommand()
                    speak('What should I say? ')
                    content = takecommand()()

                    server = smtplib.SMTP('smtp.gmail.com', 587)
                    server.ehlo()
                    server.starttls()
                    server.login("gmail", 'pass')
                    server.sendmail('*****@*****.**', Recipient_user,
                                    content)
                    server.close()
                    speak('Email sent!')

                except:
                    speak('Sorry boss i cant send this email right now!')
            pause.seconds(1)

        elif 'hide file' in voice_data or 'hide all file' in voice_data or 'hide files' in voice_data or 'visible file' in voice_data or 'unhide all  files' in voice_data:
            if 'hide' in voice_data:
                os.system("attrib +h /s /d")
                cms = 'all files are hidden', 'i hidden all the files', 'all files are hidden now'
                speak(random.choice(cms))
            if 'visibile' in voice_data:
                os.system('attrib +h /s /d')

        elif ('what' in voice_data or 'who' in voice_data
              or 'when' in voice_data or 'how' in voice_data
              or 'where' in voice_data or 'tell' in voice_data):
            if 'what is the time' in voice_data:
                main()
            if 'how are you' in voice_data:
                main()
            if 'tell me the time' in voice_data:
                main()
            if 'what is weather' in voice_data:
                main()
            if 'tell me the weather' in voice_data:
                main()
            try:
                try:
                    speak('Getting information')
                    res = cleint.query(voice_data)
                    results = next(res.results).text
                    speak(results)
                except:
                    results = wikipedia.summary(voice_data, sentences=2)
                    speak('Got it.')
                    speak('WIKIPEDIA says - ')
                    speak(results)
            except Exception:
                speak("sorry i don't know that")
    except Exception:
        msgg = 'sorry i cant do that right now', 'error404'
        speak(random.choice(msgg))
Ejemplo n.º 26
0
def run():

    # DELETE OLD VIDEO

    try:
        os.remove('input.mp4')
    except OSError:
        pass

    try:
        os.remove('input_2.mp4')
    except OSError:
        pass

    try:
        os.remove('input_early.mp4')
    except OSError:
        pass

    try:
        os.remove('final.mp4')
    except OSError:
        pass

    # Try to download a clip
    i = 0
    videoChoice = youTubeSearch()
    yt = None

    while yt is None:
        try:
            yt = YouTube(videoChoice)
        except:
            print("YOUTUBE SEARCH: Trying again...")
            i = i + 1
            if i > 5:
                print("YOUTUBE SEARCH: Trying something else... \n")
                videoChoice = youTubeSearch()
                i = 0
            pass

    # Choose the lowest quality we can find & download
    # quality = str(yt.filter('mp4')[-1])
    video = yt.streams.filter(
        progressive=True, file_extension='mp4',
        res='360p').first().download(filename='input_early')
    print("YOUTUBE: Choosing 360p \n")

    # EDIT VIDEO

    clipArea = int(VideoFileClip("input_early.mp4").duration /
                   2)  # pick from the middle of the video

    # clip to 5 sec
    ffmpeg_path = imageio.plugins.ffmpeg.get_exe()
    print('ffmpeg found at ' + ffmpeg_path)

    command = ffmpeg_path + " -i input_early.mp4 -ss " + str(
        clipArea) + " -t 5 input.mp4"
    print("FFMPEG: Clipping down to 5 sec \n")
    os.system(command)

    # pull it in for manipulation
    clip = VideoFileClip("input.mp4")

    # add in our audio clip
    audioclip = AudioFileClip("recordscratch_vo.wav")
    comp = concatenate_audioclips([clip.audio, audioclip])

    # make that freeze frame
    endtime = clip.duration - 0.1  # the videos ffmpeg exports aren't always exact in time, this ensures we get a freeze frame as close to the end as possible
    freezeframe = clip.to_ImageClip(t=endtime)
    screensize = clip.size
    freezeclip = freezeframe.resize(
        height=screensize[1] * 4).resize(lambda t: 1 + 0.01 * t).set_position(
            ('center', 'center')).set_duration(8)
    freezeclip = CompositeVideoClip([freezeclip]).resize(width=screensize[0])
    freezevid = CompositeVideoClip([freezeclip.set_position(('center', 'center'))], size=screensize)\

    while clip.reader.proc.poll() is not None:
        print('b')
    while audioclip.reader.proc.poll() is not None:
        print('a')

    # combine and export video
    try:
        final_clip = concatenate_videoclips(
            [clip, freezevid]).set_duration(13).set_audio(comp)
        print('Making final video')
        final_clip.write_videofile("final.mp4", audio_codec='aac')
    except Exception as e:
        pass
    finally:
        # cleaning up
        clip.reader.close()
        audioclip.reader.close_proc()

    clip.reader.close()
    audioclip.reader.close_proc()

    pause.seconds(5)

    # TWEET IT
    print('Sending tweet!')
    twitter = Twython(APP_KEY, APP_SECRET, ACCESS_KEY, ACCESS_SECRET)

    tweetCopy = [
        "*record scratch*\n*freeze frame*\nYup, that's me. You're probably wondering how I ended up in this situation."
    ]

    video = open('final.mp4', 'rb')
    response = twitter.upload_video(media=video, media_type='video/mp4')

    tweet = twitter.update_status(status=random.choice(tweetCopy),
                                  media_ids=[response['media_id']])
    twitter.update_status(status=('@' + tweet['user']['screen_name'] +
                                  ' SOURCE VIDEO: ' + videoChoice),
                          in_reply_to_status_id=tweet['id'])
Ejemplo n.º 27
0
        for i in range(5):
            print(6 / 3)
            pause.seconds(1)


class mul(Thread):
    def run(self):
        for i in range(5):
            print(6 * 3)
            pause.seconds(1)


t1 = add()
t2 = sub()
t3 = div()
t4 = mul()

t1.start()
pause.seconds(0.2)
t2.start()
pause.seconds(0.2)
t3.start()
pause.seconds(0.2)
t4.start()

t1.join()
t2.join()
t3.join()
t4.join()

print("Bye")
Ejemplo n.º 28
0
 def run(self):
     for i in range(5):
         print(2 + 3)
         pause.seconds(1)
Ejemplo n.º 29
0
                    cv2.FONT_HERSHEY_SIMPLEX, 0.45,
                    (255, 255, 255), 2)
        cv2.putText(frameClone, label, (fX, fY - 10),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
        cv2.rectangle(frameClone, (fX, fY), (fX + fW, fY + fH),
                      (0, 0, 255), 2)
    # for c in range(0, 3):
    #        frame[200:320, 10:130, c] = emoji_face[:, :, c] * \
    #        (emoji_face[:, :, 3] / 255.0) + frame[200:320,
    #        10:130, c] * (1.0 - emoji_face[:, :, 3] / 255.0)



        if(emotion=="happy"):
           # playsound.playsound('m11.mp3', True)
            pause.seconds(0.5)


        elif (emotion == "disgust"):
           # playsound.playsound('m11.mp3', True)
            pause.seconds(0.5)

            # print("DIGUSTING")
        elif (emotion == "scared"):
            #playsound.playsound('m11.mp3', True)
            pause.seconds(0.5)

            # print("SCARRY")
        elif (emotion == "angry"):
           # playsound.playsound('m11.mp3', True)
            pause.seconds(0.5)
Ejemplo n.º 30
0
 def _delay(self, amount):
     pause.seconds(amount)
Ejemplo n.º 31
0
def scrape(driver, url):

    #final data to csv
    userNamesFinal = list()
    userJobsFinal = list()
    userLocationsFinal = list()
    pairedUserLinksFinal = list()

    #declare temp data
    userNames = list()
    userJobs = list()
    userLocations = list()
    userLinks = list()
    pairedUserLinks = list()

    firstElem = 0
    lastElem = 11

    PROFILE_DETECT = '/in/'

    PROFILE_DETECT2 = 'https://www.linkedin.com/in/'

    for page in range(1, 6):

        driver.get(url)
        pos.seconds(8)
        soup = BeautifulSoup(driver.page_source, 'lxml')

        print("Page loaded")
        main_window = soup.find("div", {"class": "search-results ember-view"})

        list_window = main_window.find("div", {
            "class":
            "blended-srp-results-js pt0 pb4 ph0 container-with-shadow"
        })

        findUsers = list_window.findAll(
            "li",
            {"class": "search-result search-result__occluded-item ember-view"})

        # begin new sector

        #restart temp data
        userNames = []
        userJobs = []
        userLocations = []
        userLinks = []
        pairedUserLinks = []

        # template starts here

        for location in range(firstElem, lastElem):
            try:
                app = findUsers[location].find(
                    "p", {
                        "class":
                        "subline-level-2 t-12 t-black--light t-normal search-result__truncate"
                    }).text
                refinedString = app.replace(app[0], "")
                print(refinedString)
                userLocations.append(refinedString)
            except:
                userLocations.append('N/A')

        for job in range(firstElem, lastElem):
            try:
                app = findUsers[job].find(
                    "p", {
                        "class":
                        "subline-level-1 t-14 t-black t-normal search-result__truncate"
                    }).text
                refinedString = app.replace(",", ";").replace(app[0], "")
                refinedStringnew = str(refinedString)
                userJobs.append(refinedStringnew)
            except:
                userJobs.append('N/A')

        for name in range(firstElem, lastElem):
            try:
                app = findUsers[name].find(
                    "h3", {
                        "class":
                        "actor-name-with-distance search-result__title single-line-truncate ember-view"
                    }).find("span", {
                        "class": "name actor-name"
                    }).text
                userNames.append(str(app))
            except:
                userNames.append('Linkedin Member')

#        for link in soup.findAll('a', href=True):
#            if (PROFILE_DETECT in link['href'] or PROFILE_DETECT2 in link['href'] ):
#                print(link['href'])
#                userLinks.append(str(link['href']))

        for link in soup.findAll('a', href=True):
            if (PROFILE_DETECT in link['href']):
                print(link['href'])
                fullLink = 'https://www.linkedin.com' + str(link['href'])
                userLinks.append(fullLink)
            elif (PROFILE_DETECT2 in link['href']):
                print(link['href'])
                userLinks.append(str(link['href']))

        userLinks = list(dict.fromkeys(userLinks))  # remove duplicates

        # if userLinks is empty

        if (len(userLinks) == 0):
            for nothing in range(firstElem, lastElem):
                pairedUserLinks.append('N/A')
        else:
            index = 0
            for selected_name in range(firstElem, lastElem):

                if (userNames[selected_name] not in 'Linkedin Member'):

                    try:
                        this_user = userLinks[index]
                        pairedUserLinks.append(this_user)
                    except:
                        print("nothing")
                        pairedUserLinks.append("N/A")
                    index += 1
                else:
                    pairedUserLinks.append("N/A")

        # end new sector

        nextBTN = driver.find_element_by_xpath(
            '//*[@class="artdeco-pagination__button artdeco-pagination__button--next artdeco-button artdeco-button--muted artdeco-button--icon-right artdeco-button--1 artdeco-button--tertiary ember-view"]'
        )
        nextBTN.click()

        #append temp data to array

        userNamesFinal.extend(userNames)
        pairedUserLinksFinal.extend(pairedUserLinks)

        userLocationsFinal.extend(userLocations)  # this line seems defective

        userJobsFinal.extend(userJobs)

        pos.seconds(1)
        nextURL = driver.current_url
        url = nextURL


#    filterThis = 'Linkedin Member'
#
#    for elem in userNames:
#        if (userNames[elem] in filterThis):
#            del userNames[elem]
#            del userJobs[elem]
#            del userLocations[elem]
#            del userLinks[elem]

# end of big loop

    final_data = pd.DataFrame({
        'USER': userNamesFinal,
        'JOBP': userJobsFinal,
        'LOCT': userLocationsFinal,
        'LINK': pairedUserLinksFinal
    })

    final_data.append(final_data, ignore_index=True)

    final_data.to_csv(
        'C:\\Users\\Pipo\\Documents\\Python Scripts\\CANDIDATOS\\scraped_candidates.csv'
    )

    print(final_data)
Ejemplo n.º 32
0
def run(driver,
        shoe_type,
        username,
        password,
        url,
        shoe_size,
        shipping_option,
        login_time=None,
        release_time=None,
        shipping_address=None,
        page_load_timeout=None,
        screenshot_path=None,
        html_path=None,
        select_payment=False,
        purchase=False,
        num_retries=None,
        dont_quit=False,
        cvv=None):
    driver.maximize_window()
    driver.set_page_load_timeout(page_load_timeout)

    if login_time:
        LOGGER.info("Waiting until login time: " + login_time)
        pause.until(date_parser.parse(login_time))

    skip_retry_login = True
    try:
        login(driver=driver, username=username, password=password)
    except TimeoutException:
        LOGGER.info("Failed to login due to timeout. Retrying...")
        skip_retry_login = False
    except Exception as e:
        LOGGER.exception("Failed to login: "******"Failed to retry login: "******"Waiting until release time: " + release_time)
        wait_duration = (date_parser.parse(release_time) -
                         datetime.datetime.now()).total_seconds()
        pause.seconds(int(wait_duration))
    skip_add_address = False
    skip_select_shipping = False
    skip_payment = False
    num_retries_attempted = 0
    while True:
        try:
            try:
                LOGGER.info("Requesting page: " + url)
                driver.get(url)
                LOGGER.info("Noam: requesting 1")
            except TimeoutException:
                LOGGER.info("Page load timed out but continuing anyway")

            try:
                skip_size_selection = False
                substring = "size="
                if substring in url:
                    skip_size_selection = True
                select_shoe_size(driver=driver,
                                 shoe_size=shoe_size,
                                 shoe_type=shoe_type,
                                 skip_size_selection=skip_size_selection)
            except Exception as e:
                # Try refreshing page since you can't click Buy button without selecting size (except if size parameter passed in)
                LOGGER.exception("Failed to select shoe size: " + str(e))
                continue

            try:
                click_buy_button(driver=driver)
            except Exception as e:
                LOGGER.exception("Failed to click buy button: " + str(e))
                six.reraise(Exception, e, sys.exc_info()[2])

            skip_add_address, skip_select_shipping, skip_payment = poll_checkout_phase_one(
                driver=driver)

            if skip_add_address is False and shipping_address:
                try:
                    click_add_new_address_button(driver=driver)
                except Exception as e:
                    LOGGER.exception(
                        "Failed to click Add New Address button: " + str(e))
                    six.reraise(Exception, e, sys.exc_info()[2])

                try:
                    input_address(driver=driver,
                                  shipping_address=shipping_address)
                except Exception as e:
                    LOGGER.exception("Failed to select address: " + str(e))
                    six.reraise(Exception, e, sys.exc_info()[2])

                try:
                    click_save_button(driver=driver)
                except Exception as e:
                    ##LOGGER.exception("Failed to click save button: " + str(e))
                    LOGGER.info("Noam: ERROR SAVE_BUTTON 1")
                    six.reraise(Exception, e, sys.exc_info()[2])

            if skip_select_shipping is False:
                try:
                    select_shipping_option(driver=driver,
                                           shipping_option=shipping_option)
                except Exception as e:
                    LOGGER.exception("Failed to select shipping option: " +
                                     str(e))
                    six.reraise(Exception, e, sys.exc_info()[2])

                try:
                    click_save_button(driver=driver)
                except StaleElementReferenceException:
                    LOGGER.info(
                        "Failed to click save button (StaleElementReferenceException). Retrying once..."
                    )
                    try:
                        click_save_button(driver=driver, check_disabled=False)
                    except Exception as e:
                        LOGGER.exception("Failed to click save button: " +
                                         str(e))
                        six.reraise(Exception, e, sys.exc_info()[2])
                except Exception as e:
                    ##LOGGER.exception("Failed to click save button: " + str(e))
                    LOGGER.info("Noam: ERROR SAVE_BUTTON 2")
                    six.reraise(Exception, e, sys.exc_info()[2])

                skip_payment = poll_checkout_phase_two(driver=driver)

            if skip_payment is False:
                if select_payment:
                    try:
                        select_payment_option(driver=driver)
                    except Exception as e:
                        LOGGER.exception("Failed to select payment option: " +
                                         str(e))
                        six.reraise(Exception, e, sys.exc_info()[2])

                if cvv:
                    try:
                        input_cvv(driver=driver, cvv=cvv)
                    except Exception as e:
                        LOGGER.exception("Failed to input cvv: " + str(e))
                        six.reraise(Exception, e, sys.exc_info()[2])

                try:
                    # Use explicit xpath since iframe from cvv causes issues with normal xpath
                    xpath = "/html/body/div[2]/div/div/div[2]/div/div/div/div/div[2]/div/div/div[2]/div/span/span[1]/div/button"
                    click_save_button(driver=driver, xpath_o=xpath)
                except Exception as e:
                    LOGGER.exception("Failed to click save button: " + str(e))
                    LOGGER.info("Noam: ERROR SAVE_BUTTON 3")
                    six.reraise(Exception, e, sys.exc_info()[2])
        ###CAN CAUSE A PROBLEM
            if purchase:
                try:
                    # Use explicit xpath since iframe from cvv causes issues with normal xpath
                    xpath = SUBMIT_BUTTON_XPATH
                    click_submit_button(driver=driver, xpath_o=xpath)
                except Exception as e:
                    LOGGER.exception("Failed to click submit button: " +
                                     str(e))
                    six.reraise(Exception, e, sys.exc_info()[2])

            LOGGER.info("FINISH.")
            break
            ##END BOT

            ##RETRING PURCHASE
        except Exception:
            if num_retries and num_retries_attempted < num_retries:
                """
                num_retries_attempted += 1
                skip_add_address = False
                skip_select_shipping = False
                skip_payment = False
                continue
                """
                LOGGER.info("Noam: Faild")
                break
            else:
                LOGGER.info("Purchase failed")
                break

    if screenshot_path:
        LOGGER.info("Saving screenshot")
        driver.save_screenshot(screenshot_path)

    if html_path:
        LOGGER.info("Saving HTML source")
        with open(html_path, "w") as f:
            f.write(driver.page_source)

    if dont_quit:
        LOGGER.info("Preventing driver quit...")
        input("Press Enter to quit...")

    driver.quit()
Ejemplo n.º 33
0
    my_img = np.zeros_like(img_crop)

    rcord=set()
    
    for j in range(y_crop):
        for k in range(x_crop):
            if(((img_crop[j,k,0]==255) and (img_crop[j,k,1]==0) and (img_crop[j,k,2]==0)) or ((img_crop[j,k,0]==247) and (img_crop[j,k,1]==27) and (img_crop[j,k,2]==27))):
                my_img[j,k,0] = 0
                my_img[j,k,1] = 255
                my_img[j,k,2] = 0
                rcord.add(k)  # record the x-coordinates of your red-color cells in a set
                
    # sort the elements in the set in ascending order and make a list

    rcord = sorted(rcord)
    target, src = srcTarget(rcord)
    
    dist = abs(src-target)
    rate = 1.0475 * (screen_width/1080)
    time = str(int(dist/rate))
    
    print(dist)
    
    """   just fix some x, y coordinate to swipe on the screen, with time already calculated before  """ 

    x = str(int(np.ceil(530*yf)))
    y = str(int(np.ceil(830*xf)))

    os.system('adb shell input touchscreen swipe ' + x + ' ' + x + ' ' + y + ' ' + y + ' ' + time)
    pause.seconds(2)