コード例 #1
0
    def check_for_objects():

        last_epoch = 0.0
        email_update_interval = 120
        try:
            while True:
                frame, found_obj = video_camera.get_object(object_classifier)
                frames, found_face = video_camera.get_object(face_classifier)
                if found_obj and (time.time() -
                                  last_epoch) > email_update_interval:
                    last_epoch = time.time()
                    print("detected body")
                    print("Sending email...")
                    sendEmail(frame)
                    print("done!")

                elif found_face and (time.time() -
                                     last_epoch) > email_update_interval:
                    last_epoch = time.time()
                    print("Detected Face")
                    print("Sending email...")
                    sendEmail(frames)
                    print("done!")
                    return
        except:
            print(("Error sending email: "), sys.exc_info()[0])
コード例 #2
0
def check_for_objects():
    global last_epoch
    while True:
        try:
            frame, found_obj = video_camera.get_object(object_classifier)
            if found_obj and (time.time() - last_epoch) > email_update_interval:
                GPIO.output(ledYlw, GPIO.HIGH)
                last_epoch = time.time()
                print("Sending email...")
                try:
                    lcd.clear()
                    lcd.cursor_pos=(0,0)
                    lcd.write_string("Motion Detected!")
                    lcd.cursor_pos = (1,0)
                    lcd.write_string("Notifying owner")
                except:
                    print("lcd error:", sys.exc_info())
                sendEmail(frame)
                time.sleep(2)
                lcd.clear()
                print("done!")
                lcd.cursor_pos=(0,0)
                lcd.write_string("Email sent!")
                time.sleep(2)
                lcd.clear()
        except:
            print("Error sending email: ", sys.exc_info()[0])
コード例 #3
0
ファイル: app.py プロジェクト: schiluka/geniapp
def createBackgroundJob(params):
    print 'i am in createBackgroundJob'
    data = {}
    localSession = {}
    steps = []
    visitedSet = Set()
    otherId = params.get('otherId', '')
    stepCount = params['stepCount']
    includeInTop50 = params['includeInTop50']
    if otherId == '':
        for step in range(0, int(stepCount)):
                stepData = getStepProfilesThread(params['accessToken'], step, visitedSet, None, localSession)
                steps.append(stepData)
        data['profileId'] = localSession['loginProfileId']
    else:
        for step in range(0, int(stepCount)):
                stepData = getStepProfilesThread(params['accessToken'], step, visitedSet, params['otherId'], localSession)
                steps.append(stepData)
        data['profileId'] = params['otherId']

    #if top50 checked
    if includeInTop50 == 'on':
        updateTop50(localSession['stepUserLink'], stepCount, localSession['totalProfiles'])

    # Send email
    data['steps'] = steps
    sendEmail(params['email'], data)
コード例 #4
0
ファイル: main.py プロジェクト: cudadog/Smart-Security-Camera
def check_for_objects():
    global last_epoch
    global last_save_epoch
    global current_state
    global video_camera
    while True:
        #Add time checker in this thread
        future_state = lt.current_state()
        current_state = check_camera_mode(video_camera, current_state,
                                          future_state)
        vis, found_obj = video_camera.get_object()
        if found_obj == True:
            if (time.time() - last_epoch) > email_update_interval:
                last_epoch = time.time()
                print "[INFO] sending email..."
                ret, jpeg = cv2.imencode('.jpg', vis)
                frame = jpeg.tobytes()
                try:
                    sendEmail(frame)
                    print "[INFO] done!"
                except:
                    print "Error sending email: ", sys.exc_info()[0]
            if (time.time() - last_save_epoch) > save_update_interval:
                last_save_epoch = time.time()
                print "[INFO] saving hardcopy..."
                timestamp = lt.now()
                ts = timestamp.strftime("%Y-%m-%d-%H-%M-%S")
                filename = "/home/pi/Pictures/" + ts + ".jpeg"
                try:
                    cv2.imwrite(filename, vis)
                    print "[INFO] done!"
                except:
                    print "Error saving hardcopy: ", sys.exc_info()[0]
コード例 #5
0
def check_mem():
    if (print_type == 1) or isset(sys.argv, "mem"):
        memory_convent = 1024 * 1024
        mem = psutil.virtual_memory()
        mem_data = int(mem.total / (memory_convent) - mem.used / (1024 * 1024))
    if mem_data < default_mem:
        content = hostname + "(" + ip + ")" + ":服务器内存值过低,请悉知" + "\n当前内存值为:" + str(
            mem_data) + "M"
        mail.sendEmail(content)
コード例 #6
0
ファイル: p2u.py プロジェクト: mamsterla/p2u
def create_p2u_background_job(params):
    """Builds long running job"""
    global LOGGER
    if LOGGER == None:
        LOGGER = logging.getLogger()
    LOGGER.debug("create_p2u_background_job")

    LOGGER.info(
        'process path to user calling get_geni_path_to with params: %s',
        params['other_id'])
    continue_flag = True
    data = {}
    if params['other_id'] != params['target_profile_id']:
        while continue_flag:
            data = get_geni_path_to(params['access_token'],
                                    params['refresh_token'],
                                    params['other_id'],
                                    params['target_profile_id'])
            LOGGER.debug('Path data returned: %s', str(data))
            if (data and str(data.get('status', '')) != 'pending'):
                continue_flag = False
            else:
                time.sleep(10)
        data['source_id'] = params['other_id']
        data['target_id'] = params['target_profile_id']
        if (str(data.get('status')) == 'done'):
            params['access_token'] = data['access_token']
            params['refresh_token'] = data['refresh_token']
            # load source and target names
            (params['access_token'], params['refresh_token'],
             source_obj) = get_other_profile(params['access_token'],
                                             params['refresh_token'],
                                             params['other_id'])
            profile_data = json.loads(source_obj)
            LOGGER.info('Source profile data returned: %s', source_obj)
            data['source_name'] = profile_data.get('name', '(unknown)')
            data['source_url'] = profile_data['profile_url']
            (params['access_token'], params['refresh_token'],
             target_obj) = get_other_profile(params['access_token'],
                                             params['refresh_token'],
                                             params['target_profile_id'])
            profile_data = json.loads(target_obj)
            LOGGER.info('Target profile data returned: %s', target_obj)
            data['target_name'] = profile_data['name']
            data['target_url'] = profile_data['profile_url']
            # TODO - handle error case for API
            sendEmail(params['email'], data)
        else:
            if (not data.get('status')):
                data['status'] = 'API Error'
            sendErrorEmail(params['email'], data)
    else:
        data['status'] = 'Source and target profiles cannot be the same'
        data['source_id'] = params['other_id']
        data['target_id'] = params['target_profile_id']
コード例 #7
0
def check_disk():
    str_data = os.popen('df -h|grep -w "/"').read()  # 获取/磁盘信息
    str_data = str_data.split()  # 转换为列表
    disk_data = str_data[4]  # 获取磁盘使用率

    if int_value(disk_data) > int_value(default_disk):
        content = hostname + "(" + ip + ")" + ":磁盘利用率过高,请悉知" + "\n当前磁盘利用率为:" + str(
            disk_data)
        mail.sendEmail(content)
    else:
        return disk_data
def check_for_objects():
    global last_sent
    while True:
        try:
            frame, found_obj = video_camera.get_object(object_classifier)
            if found_obj and (time.time() - last_sent) > email_update_interval:
                last_sent = time.time()
                sendEmail(frame)
                print ("Email Sent...")
                
        except:
            print ("Error sending email: ", sys.exc_info()[0])
コード例 #9
0
def check_for_objects():
	global last_epoch
	while True:
		try:
			frame, found_obj = video_camera.get_object(object_classifier)
			if found_obj and (time.time() - last_epoch) > email_update_interval:
				last_epoch = time.time()
				print "Mail Gonderiliyor..."
				sendEmail(frame)
				print "done!"
		except:
			print "E-posta gonderilirken hata olustu: ", sys.exc_info()[0]
コード例 #10
0
def my_callback(channel):
    frame, found_obj = video_camera.get_object(object_classifier)
    global last_epoch
    date = datetime.datetime.now()
    d = date.strftime("%S")
    print(d)
    if d != "01" and (time.time() -  last_epoch) > email_update_interval and found_obj:
      last_epoch = time.time()
      print("Detection de mouvement")
      sendEmail(frame)
    else:
      print("Rien")
コード例 #11
0
def check_for_objects():
	global last_epoch
	while True:
		try:
			frame, found_obj = video_camera.get_object(object_classifier)
			if found_obj and (time.time() - last_epoch) > email_update_interval:
				last_epoch = time.time()
				print "Sending email..."
				sendEmail(frame)
				print "done!"
		except:
			print "Error sending email: ", sys.exc_info()[0]
コード例 #12
0
ファイル: main.py プロジェクト: yscylhy/Smart-Security-Camera
def check_for_objects():
    global last_epoch
    while True:
        try:
            frame, found_obj = video_camera.get_object_pt(object_classifier, class_names)
            # frame, found_obj = video_camera.get_object_cv(object_classifier)
            if found_obj and (time.time() - last_epoch) > email_update_interval:
                last_epoch = time.time()
                print("Sending email...")
                sendEmail(fromEmail, fromEmailPassword, toEmail, frame)
                print("done!")
        except:
            print("Error sending email: ", sys.exc_info()[0])
コード例 #13
0
def sendemail(im, Id):
    global flag
    global counter
    if (flag > 0 and counter == 0):
        cv2.imwrite('test.jpg', im)
        mail.sendEmail(Id)
        print("Email Sent")
        counter = 1
    elif (flag > 0 and counter <= 50):
        counter = counter + 1
    elif (flag > 0 and counter > 50):
        flag = 0
        counter = 0
コード例 #14
0
def button_press():
    # getting the button imput from GPIO pin 2 of Raspi
    button = Button(2)

    while True:
        if button.is_pressed:
            print("Button is pressed")
            # getting the frame from the video_camera at the instant the button is pressed
            frame = video_camera.get_frame()

            # send an email with the attachment as the image
            sendEmail(frame)
            print("done!")
コード例 #15
0
ファイル: autovid.py プロジェクト: lionelwhitcombe/ASPR
def check_for_people():
    global timeStart
    while True:
        try:
            frame, found_intruder = video_camera.get_object(object_classifier)
            if found_intruder and (time.time() -
                                   timeStart) > email_update_interval:
                timeStart = time.time()
                print("Sending email...")
                sendEmail(frame)
                print("email sent")
        except:
            print("Error sending email: script process will be terminated ")
            sys.exit(0)
コード例 #16
0
def check_for_objects():
    global last_epoch
    while True:
        try:
            frame, found_obj = video_camera.get_object(object_classifier)
            if found_obj and (time.time() -
                              last_epoch) > email_update_interval:
                last_epoch = time.time()
                print("Image captured...")
                sendEmail(frame)
                print("Sending email...")
                print("done!")
        except:
            print(traceback.format_exc())
コード例 #17
0
def check_for_objects():
    global last_epoch
    # infinite loop
    while True:
        try:
            frame, found_obj = video_camera.get_object(object_classifier)
            # time() :- number of seconds elapsed since the epoch
            if found_obj and (time.time() -
                              last_epoch) > email_update_interval:
                last_epoch = time.time()
                print("Sending email...")
                sendEmail(frame)
                print("done!")
        except:
            print("Error sending email: "), sys.exc_info()[0]
コード例 #18
0
def my_callback(channel): #Fonction appelé dès lors détection d'un mouvement
    frame, found_obj = video_camera.get_object(object_classifier)
    global last_epoch
    date = datetime.datetime.now() #Récupération de la date et l'heure actuel (pour les testes et vérifications)
    d = date.strftime("%S") #Variable de récupération des secondes (str) (pour les testes et vérifications)
    print(d) #Affiche pour vérifier
    if d != "01" and (time.time() -  last_epoch) > email_update_interval : #Teste si la valeur des secondes est différentes de 01 (sinon répétition d'un mouvement toutes les minutes à 01s) et test si le temps - à la dernière détection de mouvement > interval d'envoie de mail
      last_epoch = time.time() #Changement de la valeur last_epoch par le temps du dernier mouvement
      print('Mouvement detecte  a :') #Affichage du texte dans le terminal
      date = datetime.datetime.now() #Récupération de la date et l'heure actuel
      print(date.strftime("%d-%m-%Y %H:%M:%S")) #Affichage du texte dans le terminal
      print("Envoie mail") #Affichage du texte dans le terminal
      sendEmail(frame) #Utilisation de la fonction sendEmail du fichier mail.py avec récupération de frame pour intégration dans le mail
      print("Fait") #Affichage du texte dans le terminal
    else:
      print("Rien") #Si mouvement détecter dans l'interval d'envoie de mail et si les secondes sont égales à 01 alors on affiche "Rien" dans le else pour vérification
コード例 #19
0
def check_for_objects():
    global last_epoch
    while True:
        try:
            frame, found_obj = video_camera.get_object(object_classifier)
            if found_obj and (time.time() -
                              last_epoch) > email_update_interval:
                last_epoch = time.time()
                print("Sending email...")
                sendEmail(frame)
                print("Sending MQTT message...")
                client.publish("home/door/front/motion", "ON", 0, False)
                client.publish("home/door/front/camera", frame, 0, True)
                print("done!")
        except:
            print("Error sending email: ", sys.exc_info()[0])
コード例 #20
0
ファイル: main.py プロジェクト: hemantlader/the-fourth-eye
def check_for_objects():
    if 'uid' not in session:
        pass
    else:
        global last_epoch
        while True:
            try:
                frame, found_obj, disp = video_camera.get_object(
                    object_classifier)
                #print(time.time() - last_epoch)
                if found_obj and (time.time() -
                                  last_epoch) > email_update_interval:
                    last_epoch = time.time()
                    print("Sending email...")
                    sendEmail(frame, session['uid'])
                    print("done!")
            except:
                print("Error sending email: ", sys.exc_info()[0])
コード例 #21
0
ファイル: main.py プロジェクト: ADHIKSHA/PDF-IMG
    def sendEmail():

        ### username and password of users gmail is accessed
        global username
        global password

        #to is set to receivers email ids.
        to_ = str(to.get())
        #subject of email
        subject_ = str(subject.get())
        print("username :"******"password: "******"to :" + to_)
        print("subject:" + subject_)

        #mail is composed and mail modules sendEmail funciton is called.
        #parameters sent are usrname, password, to , subject and conveted pdf files path.
        mail.sendEmail(username, password, to_, subject_, pdfpath)
        emailWin.destroy()
コード例 #22
0
ファイル: main.py プロジェクト: sasmitohrr/IOTsecuritycamera
def check_for_objects():
    global last_epoch
    while True:
        try:
            frame, found_obj = video_camera.get_object(object_classifier)
            if found_obj and (time.time() -
                              last_epoch) > email_update_interval:
                last_epoch = time.time()
                print('Sending email...')
                sendEmail(frame)
                d = now.strftime("%Y-%m-%d")
                t = now.strftime("%H:%M")
                img = base64.b64encode(frame)
                data = {'Date': d, 'Time': t, 'Image': str(img)}
                db.child('Security').push(data)
                print('done!')

        except:
            print('Error sending email: '), sys.exc_info()[0]
コード例 #23
0
def sendEmails(app):
    print("SENDING EMAILS:")
    stuList = models.Student.select().order_by(
        models.Student.roomPoints.desc())
    i = 1
    length = stuList.count()  # pylint: disable=no-value-for-parameter
    for s in stuList:
        print(f"Email to {s.zID}. {i} of {length}")
        zid = s.zID
        password = ''.join([
            random.choice(string.ascii_letters + string.digits)
            for n in range(8)
        ])
        s.password = password
        s.save()
        startTime = s.startTime.strftime("%I:%M%p %d/%m/%Y")
        mail.sendEmail(app, f'{zid}@unsw.edu.au', password, startTime)
        i += 1

    print("EMAILING DONE!")
コード例 #24
0
    def open(self, path, flags):
        full_path = self._full_path(path)
        d = dictionary.loadDictionary('register.txt')
        uid = os.getuid()
        email = d.get(
            uid
        )  #verifica se utilizador pode aceder ao ficheiro, e recebe o seu email caso possa
        if (email):
            code = int.from_bytes(os.urandom(4), byteorder="little")
            mail.sendEmail(email, code)

            host = "127.0.0.1"
            port = 9999
            ssocket = socket(AF_INET, SOCK_DGRAM)
            ssocket.bind((host, port))

            addr = (host, port)
            buf = 1024
            try:
                ssocket.settimeout(30)
                codeReceived, addr = ssocket.recvfrom(buf)

                backend = default_backend()
                key = b"\n\xa2T\x8b\x14\xc4\xe5['\x10I\x07\xff\x05\xda\xae\xe4\n9\x92 \x01\x95\x1a\xceL\x19\x9dS\xa1\xb0)"
                iv = b'\xd6\xd1\xbc\xde\rWq\x9e\x9cF\xd3\xf8\xc6U\x0f\xbc'
                cipher = Cipher(algorithms.AES(key),
                                modes.CTR(iv),
                                backend=backend)
                decryptor = cipher.decryptor()
                c = decryptor.update(codeReceived) + decryptor.finalize()

                codeDecoded = c.decode()
                intCode = int(codeDecoded, 10)
                if intCode == code:
                    ssocket.close()
                    return os.open(full_path, flags)
            except timeout:
                ssocket.close()
                return -1
        else:
            return -1
コード例 #25
0
def getPrice(passwd):
    print("test3")
    for foo in soup.find_all('div', attrs={'class': 'offer__details'}):
        print("test1")
        price = foo.find('span', attrs={'class': 'price'})
        print("test2" + price)
        price_text = price.text
        print("test3" + price_text)
        price_text = re.sub("E|U|R", "", price_text)
        print("test4" + price_text)
        price_float = float(price_text)
        print("test5" + price_float)
        priceArray.append(price_float)
        print("test6" + priceArray)

    lowest_price = min(priceArray)

    if lowest_price <= CARD_PRICE:
        sendEmail(lowest_price, url, passwd)
    time.sleep(TIMER_TIME)
    getPrice(passwd)
コード例 #26
0
def check_for_objects():  #Fonction de détection d'objet
    global last_epoch
    while True:
        try:
            frame, found_obj = video_camera.get_object(
                object_classifier
            )  #appelation la fonction de videm_camera.get_object qui est dans le fichier camera.py
            if found_obj and (
                    time.time() - last_epoch
            ) > email_update_interval:  #Test si objet trouvé et si le temps actuel - temps de la dernière > interval mail
                last_epoch = time.time(
                )  #Changement de la valeur last_epoch par le temps du dernier mouvement
                print("Envoie mail")  #Affichage du texte dans le terminal
                sendEmail(
                    frame
                )  #Utilisation de la fonction sendEmail du fichier mail.py avec récupération de frame et du found_obj pour intégration dans le mail
                print("Fait")  #Affichage du texte dans le terminal
        except:
            print(
                "PB envoie mail",
                sys.exc_info()[0]
            )  #Affiche des erreurs dans le terminal lors du non envoie du mail
コード例 #27
0
def check_for_objects():
	global last_epoch
	
	
	while True:
		try:
                        
                    upload_done_event.wait()
                    frame, found_obj = video_camera.get_object(object_classifier)
                    if found_obj and (time.time() - last_epoch) > email_update_interval:
                            last_epoch = time.time()
                            cv2.imwrite("output.jpg", frame)
                            test_img = cv2.imread("output.jpg")
                            predicted_img = predict(test_img)
                            ret, jpeg = cv2.imencode('.jpg', predicted_img)
                            
                            print "Sending email..."
                            sendEmail(jpeg.tobytes())
                            print "done!"

		except:
			print "Error sending email: ", sys.exc_info()[0]
			traceback.print_exc(file=sys.stdout)
コード例 #28
0
def getSubscribersFromEmail(**kargs):
    listName = kargs['listName']
    sympaCommandEmail = kargs['sympaCommandEmail']
    listContactEmail = kargs['listContactEmail']
    moderatorEmail = kargs['moderatorEmail']
    moderatorPassword = kargs['moderatorPassword']
    imapServer = kargs['imapServer']
    imapPort = kargs['imapPort']
    smtpServer = kargs['smtpServer']
    smtpPort = kargs['smtpPort']

    command = 'REVIEW %s' % listName
    sendAttempts = 1
    while True:
        print('[SUBSCRIBED USERS] - Sending a subscribers request to %s' % sympaCommandEmail)
        wasEmailSent = sendEmail(sympaCommandEmail, command, moderatorEmail, moderatorPassword,
            smtpServer, smtpPort)
        if wasEmailSent:
            break

        sendAttempts += 1
        if sendAttempts == 10:
            return []

    print('[SUBSCRIBED USERS] - email sent')
    time.sleep(30)

    print('[SUBSCRIBED USERS] - reading email content...')
    emails = getEmailsFromUser(listContactEmail, moderatorEmail, moderatorPassword,
        imapServer, imapPort, listName, subjectFilter='REVIEW r00thouse')

    EMAIL_SIMPLE_REGEX = '[\w\.-]+@[\w\.-]+'

    subscribedUsers = []
    for message in emails:
        content = message['content']
        content = removeEOLCharacters(content, replace=' ')
        regexResult = re.findall(EMAIL_SIMPLE_REGEX, content)

        for subsUser in regexResult:
            subscribedUsers.append(subsUser)

    return subscribedUsers
コード例 #29
0
ファイル: app.py プロジェクト: schiluka/genigfdc
def createBackgroundJob(params):
    print 'i am in createBackgroundJob'
    data = {}
    localSession = {}
    steps = []
    visitedSet = Set()
    otherId = params.get('otherId', '')
    stepCount = params['stepCount']
    includeInTop50 = params['includeInTop50']
    if otherId == '':
        for step in range(0, int(stepCount)):
                stepData = getStepProfilesThread(params['accessToken'], step, visitedSet, None, localSession)
                if includeInTop50 == 'on':
                    saveGeniProfile(stepData, localSession['stepProfileName'],
                                    localSession['guid'], localSession['stepUserLink'])
                steps.append(stepData)
                print 'Calculated logged in profile ' + localSession['guid'] +' counts for step:' + str(step + 1)

                #Send Email after each step
                data['steps'] = steps
                data['geniLink'] = localSession['stepUserLink']
                data['guid'] = localSession['guid']
                data['profileId'] = localSession['loginProfileId']
                data['profileName'] = localSession['stepProfileName']
                data['remainingSteps'] = str(int(stepCount) - int(step) - 1)
                sendEmail(params['email'], data)
    else:
        for step in range(0, int(stepCount)):
                stepData = getStepProfilesThread(params['accessToken'], step, visitedSet, params['otherId'], localSession)
                if includeInTop50 == 'on':
                    saveGeniProfile(stepData, localSession['stepProfileName'],
                                    localSession['guid'], localSession['stepUserLink'])
                steps.append(stepData)
                print 'Calculated other profile ' + localSession['guid'] +' counts for step:' + str(step + 1)
                data['profileId'] = params['otherId']
                data['steps'] = steps
                data['geniLink'] = localSession['stepUserLink']
                data['guid'] = localSession['guid']
                data['profileName'] = localSession['stepProfileName']
                data['remainingSteps'] = str(int(stepCount) - int(step) - 1)
                sendEmail(params['email'], data)

    data['steps'] = steps
    data['geniLink'] = localSession['stepUserLink']
    data['guid'] = localSession['guid']
    sendEmail(params['email'], data)
コード例 #30
0
ファイル: views.py プロジェクト: nmalbran/vidascopio
    def post(self, request):
        form = ContactoForm(request.POST)
        if form.is_valid():
            body = """
            Mensaje enviado desde vidascopio.cl

            Nombre: %(nombre)s
            Mail: %(mail)s
            Telefono: %(telefono)s
            Mensaje:
            %(mensaje)s
            """ % form.cleaned_data

            subject = "Contacto de '%s' desde Vidascopio.cl" % form.cleaned_data['nombre']
            sender = "*****@*****.**"
            to = os.environ.get('CONTACTO_EMAIL_TO')

            enviado = sendEmail(subject, sender, to, body)

            if enviado:
                return render_to_response('web2/contacto_fin.html', context_instance=RequestContext(request))

        return render_to_response(self.template_name, {'form': form}, context_instance=RequestContext(request))
コード例 #31
0
ファイル: app.py プロジェクト: mamsterla/gfdc
def create_background_job(params):
    """Builds long running job for more than 4 step requests"""
    global LOGGER
    if LOGGER == None:
        LOGGER = logging.getLogger()
    LOGGER.debug("create_background_job")
    data = {}
    local_session = {}
    steps = []
    visited_set = Set()
    other_id = params.get('other_id', '')
    step_count = params['step_count']
    include_in_top50 = params['includeInTop50']
    LOGGER.debug('create_background_job step_count: %s', step_count)
    if other_id == '':
        for step in range(0, int(step_count)):
            step_data = get_step_profiles_thread(params['access_token'],
                                                 params['refresh_token'], step,
                                                 visited_set, None,
                                                 local_session)
            params['access_token'] = step_data['access_token']
            params['refresh_token'] = step_data['refresh_token']
            if include_in_top50 == 'on':
                save_geni_profile(step_data, local_session['stepProfileName'],
                                  local_session['guid'],
                                  local_session['stepUserLink'])
            steps.append(step_data)
            LOGGER.debug('Calculated logged in profile %s counts for step %s',
                         local_session['guid'], str(step + 1))

            #Send Email after each step
            data['steps'] = steps
            data['profile_id'] = local_session['loginProfileId']
            data['geniLink'] = local_session['stepUserLink']
            data['guid'] = local_session['guid']
            data['profileName'] = local_session['stepProfileName']
            data['remainingSteps'] = str(int(step_count) - int(step) - 1)
            sendEmail(params['email'], data)
    else:
        for step in range(0, int(step_count)):
            step_data = get_step_profiles_thread(params['access_token'],
                                                 params['refresh_token'], step,
                                                 visited_set,
                                                 params['other_id'],
                                                 local_session)
            params['access_token'] = step_data['access_token']
            params['refresh_token'] = step_data['refresh_token']
            if include_in_top50 == 'on':
                save_geni_profile(step_data, local_session['stepProfileName'],
                                  local_session['guid'],
                                  local_session['stepUserLink'])
            steps.append(step_data)
            LOGGER.debug('Calculated logged in profile %s counts for step %s',
                         local_session['guid'], str(step + 1))
            data['steps'] = steps
            data['profile_id'] = params['other_id']
            data['geniLink'] = local_session['stepUserLink']
            data['guid'] = local_session['guid']
            data['profileName'] = local_session['stepProfileName']
            data['remainingSteps'] = str(int(step_count) - int(step) - 1)
            sendEmail(params['email'], data)

    data['steps'] = steps
    data['geniLink'] = local_session['stepUserLink']
    data['guid'] = local_session['guid']
コード例 #32
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import time
import mail
import os
import urllib

if __name__ == "__main__":
    authInfo = {}
    authInfo['server'] = 'smtp.sina.com.cn'
    authInfo['user'] = '******';
    authInfo['password'] = '******'
    fromAdd = '*****@*****.**'
    toAdd = '*****@*****.**'
    subject = u'来自排行系统的监控邮件'
    plainText = '这里是普通文本'
    htmlText = time.time()
    mail.sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText)

コード例 #33
0
ファイル: tasks.py プロジェクト: zhthb2087/PythonLibUsageTest
def check_key(key):
    data_set = dao.get_last_values(key)
    if data_set is not None and utils.check_key_time_range(data_set):
        print 'error', key
        logger.error('key:' + key)
        mail.sendEmail(data_set)
コード例 #34
0
def check_for_objects():
    global pan
    global tilt
    global tilt_offset
    playStartSound()
    global last_epoch
    global last_se
    global last_report
    global lastKnownPan
    global lastKnownTilt
    global lastKnownTime
    global lost
    global lastRandomSweep
    print 'searching for objects'

    while True:
        time.sleep(update_interval)
        frame, found_obj, xLocation, yLocation, classifier_used, height, width = video_camera.get_object(
            classifiers)

        if not found_obj and (time.time() - lastKnownTime) < searchTime and (
                time.time() - lastKnownTime) > 1:
            offset = 30
            pan = lastKnownPan + random.randint(-30, 30)
            tilt = lastKnownTilt + random.randint(-30, 30)
            pantilthat.tilt(clamp(tilt, -70, 70))
            pantilthat.pan(clamp(pan, -90, 90))
            if not lost:
                soundThread3 = threading.Thread(target=playMineEffect, args=())
                soundThread3.start()
                lost = True
        elif not found_obj and (time.time() - lastKnownTime) > 1 and (
                time.time() - lastRandomSweep) > sweepTime:
            lastRandomSweep = time.time()
            pan = random.randint(-90, 90)
            tilt = random.randint(-70, 70)
            pantilthat.tilt(clamp(tilt, -30, 30))
            pantilthat.pan(clamp(pan, -90, 90))

        if found_obj and (time.time() - last_epoch) > update_interval:
            classifiers_usage[classifier_used] += 1
            last_epoch = time.time()
            pan -= (xLocation / (width / -60)) + 30
            tilt -= ((yLocation + tilt_offset) / (height / -60)) + 30

            lastKnownPan = pan
            lastKnownTilt = tilt
            pantilthat.pan(clamp(pan, -90, 90))
            pantilthat.tilt(clamp(tilt, -70, 70))
            #print used_secondary
            #print 'x: %s' % (xLocation)
            #print 'y: %s' % (yLocation)
            #print "Sending email..."
            sendEmail(frame)
            lastKnownTime = time.time()
            if lost and (time.time() - last_report) > report_interval:
                lost = False
                soundThread = threading.Thread(target=playOverwatch, args=())
                soundThread.start()
                last_report = time.time()

            if (time.time() - last_se) > se_interval:
                soundThread2 = threading.Thread(target=playSoundEffect,
                                                args=())
                soundThread2.start()
                last_se = time.time()