Example #1
0
def compute_list(board_name, list_name, action):
    cards_list = []
    lists_name = []
    board_members = fetch_members_by_board()
    card_id_list = fetch_list_id_by_board(list_name)

    for i, card_list in enumerate(card_id_list):
        if not g_crontab_style:
            output_str = "\rfetching card info %d/%d" % (i + 1, len(card_id_list))
            sys.stdout.write(output_str)
        cards_info = get_cards_info(card_list['id'], board_members)
        [h.update({'list_name': card_list['name']}) for h in cards_info]
        cards_list.extend(cards_info)
        lists_name.append(card_list['name'])

    print("")
    list_name = " & ".join(lists_name)

    if len(cards_list):
        cards_dict = cardinfo_turn_to_dict(cards_list)

        if action == "new_iteration" or action == "daily_cards":
            save_cardinfo_to_json(cards_dict, board_name, action)
        else:
            workloads = sum_workloads(cards_dict, board_name)
            show(board_name, list_name, workloads)
            chartstat.draw_bar_chart(workloads)
            sendemail.send_email(board_name, g_sender, g_receiver, g_username, g_password)
    else:
        print('The list is empty!')
Example #2
0
def main():
	# Get path and metrics data from stored procedures
	df_p, df_m = stored_procedures()

	# Format data percentages
	df_p.loc[df_p['MetricType'] == 'percent', 'MetricValue'] = \
		df_p.loc[df_p['MetricType'] == 'percent', 'MetricValue'].astype(str) + '%%'

	df_m.loc[df_m['MetricType'] == 'percent', 'MetricValue'] = \
		df_m.loc[df_m['MetricType'] == 'percent', 'MetricValue'].astype(str) + '%%'

	df_p[percent_p] = df_p[percent_p].astype(str) + '%%'
	df_m[percent_m] = df_m[percent_m].astype(str) + '%%'

	df_p.drop('MetricType', axis=1, inplace=True)
	df_m.drop('MetricType', axis=1, inplace=True)

	data_p, depth_p = setup_p_data(df_p)
	data_m, depth_m = setup_m_data(df_m)

	wb = create_workbook(data_p, data_m)

	format_workbook(wb, start_p, start_m, tree_p, tree_m, depth_p, depth_m)

	send_email(send_from, send_to, subject, message, files=[file_out],
			  			server=server, port=port, username=username,
			  			password=password, use_tls=True)
Example #3
0
def front_response(user_message):
    global candid
    global y_res
    if hi_test(user_message):
        speak("please provide your candidate Id :", speech_flag)
        return "please provide your candidate Id :"
    elif candidateid_test(user_message):
        candid = user_message
        speak(
            "Shall I take your Photo and send to Recruitment team to inform about your arrival ? select (y/n)",
            speech_flag)
        return "Shall I take your Photo and send to Recruitment team to inform about your arrival ? select (y/n)"
    elif yes_test(user_message) == "y":
        y_res = user_message
        capture_image(candid)
        speak("Please wait while we send email to the recruitment team.......",
              speech_flag)
        send_email(candid, True)
        speak(
            "Thankyou, Recruitment team has been informed about your arrival. Your interview will start in about 20 mintes. Please be seated in the waiting area, recruitment team will call your name.",
            speech_flag)
        return "Thankyou, Recruitment team has been informed about your arrival.<br>Your interview will start in about 20 mintes.<br>Please be seated in the waiting area, recruitment team will call your name."

    elif yes_test(user_message) == "n":
        speak('No Problem! we have not captured your photo.', speech_flag)
        speak("Please wait while we send email to the recruitment team.......",
              speech_flag)
        send_email(candid, False)
        speak(
            "Thankyou, Recruitment team has been informed about your arrival. Your interview will start in about 20 mintes. Please be seated in the waiting area, recruitment team will call your name.",
            speech_flag)
        return "Thankyou, Recruitment team has been informed about your arrival.<br>Your interview will start in about 20 mintes.<br>Please be seated in the waiting area, recruitment team will call your name."

    else:
        return "Im am not trained for this input"
Example #4
0
def send_token(email, token):
    """Creates a email to the recipient with the token"""
    with open("templates/email_password_recovery.txt", mode="r") as file_pointer:
        string = file_pointer.read()

    string = string % (token, email, token)
    sendemail.send_email(email, "Skvaderhack Password Recovery", string, "*****@*****.**")
Example #5
0
def ask_alert(exchange_name, threshold, send_email=False):
    exchange = get_exchange_from_name(exchange_name)
    exchange_ask = exchange.getAsk()
    message = exchange.name + ' ask is ' + str(exchange_ask)
    print('\n' + message)

    if exchange_ask <= threshold or send_email:
        print('Sending email')
        se.send_email(message, message)
Example #6
0
def main():
    diff = mark_parser.get_diff()
    msg = ""

    msg = "Hello,\n\n"
    for key in diff:
        value = diff[key]
        msg += ("Column \"%s\" in %s\'s grade book changed from %s to %s.\n" %
                (key, course, str(diff[key][0]), str(diff[key][1])))

    msg += "\nCongrats! :)"

    if diff:
        sendemail.send_email(msg)
Example #7
0
def success():
    if request.method == 'POST':
        email = request.form['email_name']
        height = request.form["height_name"]
        if db.session.query(Data).filter(Data.email_ == email).count() == 0:
            data = (Data(email, height))
            db.session.add(data)
            db.session.commit()
            average_height = db.session.query(func.avg(data.height_)).scalar()
            average_height = round(average_height, 1)
            count = db.session.query(Data.height_).count()
            send_email(email, height, average_height, count)
            return render_template("success.html")
        else:
            return render_template("index.html", text="Email already in use")
Example #8
0
def success():
    if request.method == 'POST':
        email = request.form["email_name"]
        height = request.form["height_name"]

        if db.session.query(Data).filter(Data.email == email).count() == 0:
            data = Data(email, height)
            db.session.add(data)
            db.session.commit()
            avg_height = round(
                db.session.query(func.avg(Data.height)).scalar(), 1)
            send_email(email, height, avg_height)
            return render_template("success.html")
        else:
            return render_template(
                "web.html", text="We already have this email id registered")
Example #9
0
    def do_ticket_generate(self, *args):
        try:
            email = input("Enter your email: ")
            event_id = int(input("Enter the eventID: "))
            
            valid = True 
            data.create_tickets(valid, email, event_id)

            table = data.get_ticket(event_id)
            
            # if there is no email i run ticket_send.
            if email == "":
                return self.do_ticket_send()        
            else: 
                send_email(email, table)
        except:
            print(colored("The event ID does not exist."))
Example #10
0
def front_response(user_message):
    global candid
    global y_res
    global new_cand_flag
    if hi_test(user_message):
        # speak("Hello, Welcome to JP Morgan Chase & Co., please provide your candidate Id (in format e.g. JPM12345):", speech_flag)
        # return "please provide your candidate Id (in format e.g. JPM12345):"

        speak("Hello, Welcome to J P Morgan Chase Recruitment Drive", speech_flag)
        speak("Are you a new candidate, or returning candidate and want to know previous interview feedback ? type (new/returned)", speech_flag)
        return "Are you a new candidate or returning candidate and want to know previous interview feedback ? type (new/returned)?"
    elif new_returning_candidate_test(user_message) in ["n","r"]:
        speak("Please provide your candidate Id, (in format e.g. JPM12345), you can find your Candidate Id in the interview invitation email sent by our recruitment team.", speech_flag)
        return "Please provide your candidate Id (in format e.g. JPM12345):"
    elif new_returning_candidate_test(user_message)=="r":
        speak("Please wait... while I fetch your interview feedback..", speech_flag)
        speak("Your interview was conducted by Mr. Alice White, you have cleared the interview, please wait for your next round, recruitment team will call your name. Thankyou!", speech_flag)
        return "Your interview was conducted by Mr. Alice White, you have cleared the interview, please wait for your next round, recruitment team will call your name. Thankyou!"
    elif candidateid_test(user_message):
        candid = user_message
        speak("your candidate Id is " + candid, speech_flag)
        if new_cand_flag:
            speak("I am sending email to recruitment team to inform about your arrival, are you ok if I attach your photo? type (y/n)", speech_flag)
            return "I am sending email to recruitment team to inform about your arrival, are you ok if I attach your photo? type (y/n)"
        else:
            speak("Please wait... while I fetch your interview feedback..", speech_flag)
            speak("Your interview was conducted by Mr. Alice White, you have cleared the interview, please wait for your next round, recruitment team will call your name. If you need any help or assistance, then feel free to reach out to any of our recruitment team members. Thankyou!", speech_flag)
            return "Your interview was conducted by Mr. Alice White, you have cleared the interview, please wait for your next round, recruitment team will call your name. <br>Thankyou!"
    elif yes_test(user_message) == "y":
        y_res = user_message
        speak("Please wait while I capture your photo, keep your head still and smile!!.......", speech_flag)
        capture_image(candid)
        speak("Please wait while I send email to the recruitment team.......", speech_flag)
        send_email(candid, True)
        speak("Recruitment team has been informed about your arrival. Your interview will start in about 20 minutes. Please be seated in the waiting area, recruitment team will call your name. If you need any help or assistance, then feel free to reach out to any of our recruitment team members. Thankyou!", speech_flag)
        return "Recruitment team has been informed about your arrival.<br>Your interview will start in about 20 minutes.<br>Please be seated in the waiting area, recruitment team will call your name. <br>Thankyou!"
    elif yes_test(user_message) == "n":
        speak('No Problem, I have not captured your photo.', speech_flag)
        speak("Please wait while I send email to the recruitment team.......", speech_flag)
        send_email(candid, False)
        speak("Recruitment team has been informed about your arrival. Your interview will start in about 20 minutes. Please be seated in the waiting area, recruitment team will call your name. If you need any help or assistance, then feel free to reach out to any of our recruitment team members. Thankyou!", speech_flag)
        return "Recruitment team has been informed about your arrival.<br>Your interview will start in about 20 minutes.<br>Please be seated in the waiting area, recruitment team will call your name.<br>Thankyou!"
    else:
        speak("Sorry, I am not trained for this input...", speech_flag)
        return "Sorry, I am not trained for this input..."
Example #11
0
def email_success(s_price):
    import sendemail

    # name of recipient
    recipient = ["*****@*****.**"]

    # Create the body of the message (a plain-text and an HTML version).
    text = 'there\'s a sale!! for ' + str(s_price)
    html = """\
<html>
  <body style="font-family: &quot;HelveticaNeue-Light&quot;, &quot;Helvetica Neue&quot;;">
      <div style="padding: 20px 15px;margin-bottom: 15px;margin-left: 10%;width: -webkit-calc(80% - 30px);font-family: &quot;HelveticaNeue-Light&quot;, &quot;Helvetica Neue&quot;;font-size: 14px;">
        Congrats! Your pants are on sale for """ + str(s_price) + """ 
      </div>
  </body>
</html>
"""
    sendemail.send_email(recipient, text, html)
Example #12
0
def success():
    if request.method == 'POST':
        email = request.form["email_name"]
        height = request.form["height_name"]
        if db.session.query(Data).filter(Data.email == email).count() == 0:
            data = Data(email, height)
            db.session.add(data)
            db.session.commit()
            avg_height = db.session.query(func.avg(Data.height)).scalar()
            avg_height = round(avg_height, 1)
            count = db.session.query(Data.height).count()
            send_email(email, height, avg_height, count)
            return render_template("success.html")
        return render_template(
            'index.html',
            text=
            "Sorry. It looks like we've got something from that email address already. Please try with another email."
        )
Example #13
0
def email_success(s_price):
    import sendemail

    # name of recipient
    recipient = ["*****@*****.**"]

    # Create the body of the message (a plain-text and an HTML version).
    text = 'there\'s a sale!! for ' + str(s_price)
    html = """\
<html>
  <body style="font-family: &quot;HelveticaNeue-Light&quot;, &quot;Helvetica Neue&quot;;">
      <div style="padding: 20px 15px;margin-bottom: 15px;margin-left: 10%;width: -webkit-calc(80% - 30px);font-family: &quot;HelveticaNeue-Light&quot;, &quot;Helvetica Neue&quot;;font-size: 14px;">
        Congrats! Your pants are on sale for """ + str(s_price) + """ 
      </div>
  </body>
</html>
"""
    sendemail.send_email(recipient, text, html)
Example #14
0
def send_magic_link(authtoken, recipient):
    """Sends a new authtoken to the supplied recipient"""
    if not (isinstance(authtoken, str) and isinstance(recipient, str)):
        raise TypeError("All authtoken and recipient must be strings")

    if resources.verify_email(recipient) is False:
        raise HTTPError("Bad Email Address")

    groupname = auth.verify_token(authtoken)
    if groupname is None:
        raise HTTPError("Bad authtoken", 401)

    newtoken = auth.create_authtoken(groupname)

    with open("templates/email_magic_link.txt", mode="r") as file_pointer:
        message = file_pointer.read()
    message = message % (groupname, newtoken)
    subject = "Skvaderhack Login for %s" % (groupname, )
    sender = "*****@*****.**"
    sendemail.send_email(recipient, subject, message, sender)
Example #15
0
def run():
    # If the bot does timeout then we don't want to get the same emails
    # We accomplish this by checking that the submissions are new as of run time
    # Reddit submissions are ~3 hours from Eastern Time where I live, adjust as needed
    startTime = float(time.time()) + 28800
    while True:
        try:
            for submission in reddit.subreddit(subreddit).stream.submissions():
                if submission.created > startTime:  # Check the time
                    if criteria in str(submission.title).lower():
                        print submission.title
                        print submission.url
                        print submission.shortlink
                        sendemail.send_email(
                            email, subject,
                            submission.title.split(" ", 1)[1] + "\n" +
                            submission.url + "\n" + submission.shortlink)
        except PrawcoreException:
            # Timeouts happen a lot, to keep the bot running wait 60 seconds and then start again
            time.sleep(60)
            run()
Example #16
0
   def start(self):
      while 1:# Stay connected to the server and find commands
         try:
            ircmsg = self.ircsock.recv(4096) # Receive data from the server
            if len(ircmsg) == 0 or len(ircmsg) == None:
               logging.error('Socket error from twitch')
               print 'Socket error from twitch'
               send_email('No Data From Twitch') #send error report to bot email
               raise socket.error
#            print(ircmsg) # Print what's coming from the server
            if ircmsg.find(' PRIVMSG ') != -1:
               nick = ircmsg.split('!')[0][1:]
               channel = ircmsg.split(' PRIVMSG ')[-1].split(' :')[0]
               self.channel = channel
               self.command(nick, channel, ircmsg.lower(), ircmsg)
               #ircmsg.lower = makes all commands lower-case

            if ircmsg.find('PING :') != -1: # Responds to server ping
               self.ircsock.send('PONG :pingis\n')
            
            if ircmsg.find(' NOTICE ') != -1: # Responds to server ping
               self.modcheck(ircmsg)
         
         #To end thread without error

         except socket.error as error:
            print error
            printexception()
            self.ircsock.close()
            storage.save()
            quit()

         except urllib2.HTTPError as e:
            pass
            
         except Exception as e:
            print type(e)
            printexception()
            logging.error('Thread Error\n%s\nLast message sent:%s' %(e,ircmsg))
            send_email(str(e), ircmsg) #send error report to bot email
Example #17
0
def gen_word_file(num_titles, file_name, number_threads):
    """ Writes word count results to words/file_name as csv with row format:

        word, (count in cited sentence), (count in uncited sentence)

        Writes page ids and the total number of sentences to words/file_namepid as:

        Number of sentences: (number of sentences)
        pid1
        pid2 ...

        Also emails summary: requires environ vars EMAIL_ADDRESS, EMAIL_PASSWORD, TO_EMAIL
    """
    start_time = time.time()
    titles = []
    for n in range(num_titles / 500):
        titles += wikipedia.random(500)
    if num_titles % 500:
        if num_titles % 500 == 1:
            titles += [wikipedia.random(1)
                       ]  # doesn't return a list for one title
        else:
            titles += wikipedia.random(num_titles % 500)

    # get word counts
    words, ids, tot_num_sentences = aggregate_words(titles, number_threads)
    wordfile = open('words/' + file_name, 'w')
    for (word, cite, noncite) in words:
        wordfile.write("%s %s %s\n" % (word, str(cite), str(noncite)))
    wordfile.close()
    idfile = open('words/' + file_name + 'pid', 'w')
    idfile.write("Number of sentences: %d\n" % tot_num_sentences)
    for rev_id in ids:
        idfile.write("%s\n" % str(rev_id))
    idfile.close()
    end_time = time.time()
    send_email("Finished Aggregating Words\nSearching %d titles in %d threads\nTotal Time: %f minutes\nsaved in %s" \
            % (num_titles, number_threads, (end_time - start_time) / 60, file_name))
			course_title = str(result["Results"]["DATA"][0][22])+" "+str(result["Results"]["DATA"][0][3]+" "+str(result["Results"]["DATA"][0][23]))
			# Register
			if int(result["Results"]["DATA"][0][-3]) == 0:
				r = session.get(config.bas_url+"addCourseRegistration.cfm?Term="+d["termCode"]+"&CourseCRNs="+d["course_number"]+"&Schedule=Schedule%201&WaitlistedFlags=N&Units="+unit+"&ShowDebug=0")
				msg = r.json()
				try:
					if msg["Success"] != 1:
						print("Already Registered Class "+d["course_number"])
						config.courses[:] = [x for x in config.courses if x["course_number"] != d["course_number"]]
					elif msg["RegistrationStatusCodes"]["DATA"][0][0] == "Registered":
						config.courses[:] = [x for x in config.courses if x["course_number"] != d["course_number"]]
						email = config.data["username"]+"@ucdavis.edu"
						password = config.data["password"]
						header = "Auto Course Rigisterer Report"
						success_msg = "Successfully Registered Class "+d["course_number"]
						print(success_msg)
						send_email(email,password,email,header,"Dear "+config.data["username"]+",\n\nYou Have "+success_msg+" "+course_title+" at "+time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()))
				except:
					print("Failed to Register Class "+d["course_number"])

		if len(config.courses) == 0:
			print("All classes are registered")
			break
		if not args.loop:
			break
		
		sleeptime = 30*random.randint(1,10)
		print("Try again in {0} seconds.".format(sleeptime))
		time.sleep(sleeptime)

Example #19
0
         })
     else:
         fail.append({
             'user': user['user'],
             "email": user['email'],
             "cont": "抢座失败"
         })
 for us in got:
     b = (us['user'].encode('utf-8'), us['cont'].encode('utf-8'),
          us['room'], us['seat'].encode('utf-8'))
     contents = u"学号为 %s 的同学你好:%s,阅览室为 %s ,座位号为 %s。请关注微信号 WavesBreaker,请将本邮件地址设为信任邮箱以免收不到邮件。如有疑问欢迎联系[email protected]." % (
         us['user'], us['cont'], us['room'], us['seat'])
     contents = contents.encode('utf-8', 'ignore')
     eaddres = us['email']
     try:
         send_email(us['cont'], contents, eaddres)
     except Exception as e:
         print e
 for user in fail:
     contents = '''学号为 %s 的同学你好:
             预约座位失败,原因是:%s
             请关注微信号 WavesBreaker,
             请将本邮件地址设为信任邮箱以免收不到邮件。
             如有疑问欢迎联系[email protected].''' % (
         user['user'].encode("utf-8"), user['cont'].encode("utf-8"))
     eaddres = user['email']
     try:
         send_email(user['cont'], contents, eaddres)
     except:
         pass
 print 'down'
Example #20
0
    def check_folder(self):
        " Here we check the files in the folder"

        # Populate a list with to many dictionaries as extensions to check. Each dictionary will save the
        # values of the variables needed to check
        DEFAULT_MAXIMUM_DAYS = 10
        DEFAULT_MINIMUM_SIZE_MB = 5

        EMAIL_FROM = "*****@*****.**"
        EMAIL_TO = ["*****@*****.**", "*****@*****.**"]

        extensions_dict_list = []
        tmp_extension_list = []
        tmp_include_text_in_name_dict = {}
        for each_extension in self.check_extensions:  # check_extensions is a list of dictionaries
            # each_extension is a dictionary
            new_dict = {}
            new_dict['extension'] = each_extension['extension']

            if 'maximum_days' in each_extension.keys():
                new_dict['maximum_days'] = each_extension['maximum_days']
            else:
                new_dict['maximum_days'] = DEFAULT_MAXIMUM_DAYS

            if 'minimum_size_mb' in each_extension.keys():
                new_dict['minimum_size_mb'] = each_extension['minimum_size_mb']
            else:
                new_dict['minimum_size_mb'] = DEFAULT_MINIMUM_SIZE_MB

            if 'minimum_files_number' in each_extension.keys():
                new_dict['minimum_files_number'] = each_extension[
                    'minimum_files_number']
            else:
                new_dict['minimum_files_number'] = 1

            if 'include_text_in_name' in each_extension.keys():
                tmp_include_text_in_name_dict[each_extension[
                    'extension']] = each_extension['include_text_in_name']

            tmp_extension_list.append(each_extension['extension'])

            new_dict['files_count'] = 0
            new_dict['errors_count'] = 0
            new_dict['errors_msg'] = ""

            # In extensions_dict_list we have a list of dicts with information and variables
            # about the data to check
            extensions_dict_list.append(new_dict)

        file_list = []

        # Now, we have to build a list with the files that meets the requirements. Depending of the value of
        # self.recursive, we have to check only the files into a folder, or all the files bellow the folder (recursively)
        if self.recursive_check:
            for root, dirs, files in os.walk(self.path):
                for f in files:
                    for extension in tmp_extension_list:  # here we check each extension
                        if (os.path.splitext(f)[1] == extension
                            ):  # this file meets the extension requirement
                            if not (extension
                                    in tmp_include_text_in_name_dict.keys()
                                    ) or (f.find(tmp_include_text_in_name_dict[
                                        extension]) != -1):
                                # There isn't a include_text_in_name for this extension  OR the file meets the include_text_in_name requirement
                                # In both cases, we have to check this file
                                fullpath = os.path.join(root, f)
                                file_list.append(fullpath)
        else:
            dir = os.listdir(self.path)
            for f in dir:
                for extension in tmp_extension_list:  # here we check each extension
                    if (os.path.splitext(f)[1] == extension
                        ):  # this file meets the extension requirement
                        if not (extension in tmp_include_text_in_name_dict.
                                keys()) or (f.find(
                                    tmp_include_text_in_name_dict[extension])
                                            != -1):
                            # There isn't a include_text_in_name for this extension  OR the file meets the include_text_in_name requirement
                            # In both cases, we have to check this file
                            fullpath = os.path.join(self.path, f)
                            file_list.append(fullpath)

        # Now, in "file_list" list, we have all the files that we have to check
        for fullpath in file_list:
            # We have to check which extension is, because each extension can have diferent values
            # to check
            for extension in tmp_extension_list:
                if (os.path.splitext(fullpath)[1] == extension):
                    # in extension_dict we will get the dictionary that have the variables for each extension.
                    for extension_dict in extensions_dict_list:
                        if extension_dict['extension'] == extension:
                            # in my_extension_dict we have the dictionary for the file's extension with all the needed variables
                            my_extension_dict = extension_dict
                    my_extension_dict[
                        'files_count'] += 1  # there is at least one file with this extension
                    # now we create a new instance of the BackupFile class with each file, using the values that we
                    # we have in the dictionary for each extension to check
                    thisfile = BackupFile(fullpath,
                                          extension_dict['maximum_days'],
                                          extension_dict['minimum_size_mb'])
                    if thisfile.out_of_date():
                        my_extension_dict['errors_count'] += 1
                        my_extension_dict['errors_msg'] += "File is more than " + str(
                            maximum_days
                        ) + " days old. File: " + thisfile.path + " File time " + str(
                            thisfile.filetime) + " minimum age " + str(
                                thisfile.minimum_age) + "\n\n"

                    if thisfile.incorrect_size():
                        my_extension_dict['errors_count'] += 1
                        my_extension_dict[
                            'errors_msg'] += "Check the file size, is lower than the minimum " + thisfile.path + " . File size: " + thisfile.size_in_mb + "\n\n"

                    if extension == ".bz2":  # Especifical check for bz2 files
                        if not thisfile.check_bzip():
                            my_extension_dict['errors_count'] += 1
                            my_extension_dict[
                                'errors_msg'] += "BZIP2 Error!! Check this file " + thisfile.path

        # now, we've to check if we've find files for each extension. If not, we don't have backups for this extension
        email_message = "PATH --> " + self.path + "\n\n"

        some_errors = False
        for each_extension_dict in extensions_dict_list:
            if each_extension_dict['files_count'] == 0:
                each_extension_dict['errors_count'] += 1
                each_extension_dict[
                    'errors_msg'] += "CAUTION !! There aren't " + "'" + each_extension_dict[
                        'extension'] + "'" + " copies in the backup folder\n\n"

            if each_extension_dict['files_count'] < each_extension_dict[
                    'minimum_files_number']:
                each_extension_dict['errors_count'] += 1
                each_extension_dict[
                    'errors_msg'] += "CAUTION !! There is/are only " + str(
                        each_extension_dict['files_count']
                    ) + " file/s and there would be at least " + str(
                        each_extension_dict['minimum_files_number']
                    ) + " files in the backup folder\n\n"

            if each_extension_dict['errors_count'] > 0:
                email_message += each_extension_dict['errors_msg']
                some_errors = True

        if some_errors:
            mail_subject = "Elkarbackup: Errors"
        else:
            mail_subject = "Elkarbackup: All OK"

        send_email(EMAIL_FROM, EMAIL_TO, mail_subject, email_message)
Example #21
0
def email_fail():
    import sendemail
    recipient = ["*****@*****.**"]
    text = 'not today'
    html = "not today, price is still over 49.9"
    sendemail.send_email(recipient, text, html)
Example #22
0
    def on_data(self, data):

        # decode json
        dict_data = json.loads(data)

        # pass tweet into TextBlob
        try:
            tweet = TextBlob(dict_data["text"])
        except:
            return True

        # get vader compound
        twe = dict_data['text'].encode('utf-8')
        vader = vaderSentiment(twe)['compound']

        # determine if sentiment is positive, negative, or neutral
        if tweet.sentiment.polarity < 0:
            sentiment = "negative"
        elif tweet.sentiment.polarity == 0:
            sentiment = "neutral"
        else:
            sentiment = "positive"

        days = [
            "Monday",
            "Tuesday",
            "Wednesday",
            "Thursday",
            "Friday",
            "Saturday",
            "Sunday"]
        day_nums = [x for x in range(7)]
        day_dict = dict(zip(days, day_nums))
        dict_day = dict(zip(day_nums, days))
        today = datetime.today() - timedelta(hours=4)
        daystr = dict_day[today.weekday()]

        def get_status(text):
            splitlist = text.split()
            try:
                three = splitlist[5]
                four = splitlist[6]
                if three == daystr:
                    status = splitlist[4]
                elif four == daystr:
                    status = splitlist[5]
                else:
                    status = None
                return(status)
            except:
                return(None)

        # send email if status is OUT, DOUBTFUL,
        # search every tweet for a player name with fuzzywuzzy
        badlist = ['OUT', 'DOUBTFUL']

        # if tweet is from baskmonster
        if dict_data['user']['screen_name'] == 'BaskMonster':
            # process it
            #name = get_name(dict_data)
            status = get_status(dict_data['text'])
            # if out or doubtful- send email with tweet as body
            if status in badlist:
                send_email(dict_data['text'])

        try:
            # add text and sentiment info to elasticsearch
            es.index(index="nlp2",
                     doc_type="tweet",
                     id=dict_data["id"],
                     body={  # "screen_name": dict_data["user"]["screen_name"],
                           # "@timestamp": dict_data["created_at"],
                           "id": dict_data["id"],
                           "timestamp": datetime.utcnow(),
                           "text": dict_data["text"],
                           "user": dict_data["user"],
                           "in_reply_to_user_id": dict_data["in_reply_to_user_id"],
                           "in_reply_to_user_id_str": dict_data["in_reply_to_user_id_str"],
                           "in_reply_to_screen_name": dict_data["in_reply_to_screen_name"],
                           "in_reply_to_status_id": dict_data["in_reply_to_status_id"],
                           "in_reply_to_status_id_str": dict_data["in_reply_to_status_id_str"],
                           "lang": dict_data["lang"],
                           "entities": dict_data["entities"],
                           "coordinates": dict_data["coordinates"],
                           "contributors": dict_data["contributors"],
                           "place": dict_data["place"],
                           # "quoted_status": dict_data["quoted_status"],
                           "retweet_count": dict_data["retweet_count"],
                           "retweeted": dict_data["retweeted"],
                           # "retweeted_status": dict_data["retweeted_status"],
                           # "possibly_sensitive": dict_data["possibly_sensitive"],
                           # "is_quote_status": dict_data["is_quote_status"],
                           "favorited": dict_data["favorited"],
                           "favorite_count": dict_data["favorite_count"],
                           "filter_level": dict_data["filter_level"],
                           "source": dict_data["source"],
                           "polarity": tweet.sentiment.polarity,
                           "subjectivity": tweet.sentiment.subjectivity,
                           "vader": vader,
                           "sentiment": sentiment})
            return True
        except:
            print('ERROR could not load tweet')
            return True
Example #23
0
print(
    "Please wait while we capture your photo, keep your head still and smile!!......."
)
speak(
    "Please wait while we capture your photo, keep your head still and smile!!.......",
    speech_flag)

if res == 'y':
    capture_image(candid)

    print("Please wait while we send email to the recruitment team.......")
    speak("Please wait while we send email to the recruitment team.......",
          speech_flag)

    send_email(candid)
else:
    print('\nNo Problem! we have not captured your photo.')
    speak('\nNo Problem! we have not captured your photo.', speech_flag)

print("\nThankyou, Recruitment team has been informed about your arrival")
print("Your interview will start in about 20 mintes.")
print(
    "Please be seated in the waiting area, recruitment team will call your name."
)

speak("\nThankyou, Recruitment team has been informed about your arrival.",
      speech_flag)
speak("Your interview will start in about 20 mintes.", speech_flag)
speak(
    "Please be seated in the waiting area, recruitment team will call your name.",
Example #24
0
    def on_data(self, data):

        # decode json
        dict_data = json.loads(data)

        # pass tweet into TextBlob
        try:
            tweet = TextBlob(dict_data["text"])
        except:
            return True

        # get vader compound
        twe = dict_data['text'].encode('utf-8')
        vader = vaderSentiment(twe)['compound']

        # determine if sentiment is positive, negative, or neutral
        if tweet.sentiment.polarity < 0:
            sentiment = "negative"
        elif tweet.sentiment.polarity == 0:
            sentiment = "neutral"
        else:
            sentiment = "positive"

        days = [
            "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
            "Sunday"
        ]
        day_nums = [x for x in range(7)]
        day_dict = dict(zip(days, day_nums))
        dict_day = dict(zip(day_nums, days))
        today = datetime.today() - timedelta(hours=4)
        daystr = dict_day[today.weekday()]

        def get_status(text):
            splitlist = text.split()
            try:
                three = splitlist[5]
                four = splitlist[6]
                if three == daystr:
                    status = splitlist[4]
                elif four == daystr:
                    status = splitlist[5]
                else:
                    status = None
                return (status)
            except:
                return (None)

        # send email if status is OUT, DOUBTFUL,
        # search every tweet for a player name with fuzzywuzzy
        badlist = ['OUT', 'DOUBTFUL']

        # if tweet is from baskmonster
        if dict_data['user']['screen_name'] == 'BaskMonster':
            # process it
            #name = get_name(dict_data)
            status = get_status(dict_data['text'])
            # if out or doubtful- send email with tweet as body
            if status in badlist:
                send_email(dict_data['text'])

        try:
            # add text and sentiment info to elasticsearch
            es.index(
                index="nlp2",
                doc_type="tweet",
                id=dict_data["id"],
                body={  # "screen_name": dict_data["user"]["screen_name"],
                    # "@timestamp": dict_data["created_at"],
                    "id":
                    dict_data["id"],
                    "timestamp":
                    datetime.utcnow(),
                    "text":
                    dict_data["text"],
                    "user":
                    dict_data["user"],
                    "in_reply_to_user_id":
                    dict_data["in_reply_to_user_id"],
                    "in_reply_to_user_id_str":
                    dict_data["in_reply_to_user_id_str"],
                    "in_reply_to_screen_name":
                    dict_data["in_reply_to_screen_name"],
                    "in_reply_to_status_id":
                    dict_data["in_reply_to_status_id"],
                    "in_reply_to_status_id_str":
                    dict_data["in_reply_to_status_id_str"],
                    "lang":
                    dict_data["lang"],
                    "entities":
                    dict_data["entities"],
                    "coordinates":
                    dict_data["coordinates"],
                    "contributors":
                    dict_data["contributors"],
                    "place":
                    dict_data["place"],
                    # "quoted_status": dict_data["quoted_status"],
                    "retweet_count":
                    dict_data["retweet_count"],
                    "retweeted":
                    dict_data["retweeted"],
                    # "retweeted_status": dict_data["retweeted_status"],
                    # "possibly_sensitive": dict_data["possibly_sensitive"],
                    # "is_quote_status": dict_data["is_quote_status"],
                    "favorited":
                    dict_data["favorited"],
                    "favorite_count":
                    dict_data["favorite_count"],
                    "filter_level":
                    dict_data["filter_level"],
                    "source":
                    dict_data["source"],
                    "polarity":
                    tweet.sentiment.polarity,
                    "subjectivity":
                    tweet.sentiment.subjectivity,
                    "vader":
                    vader,
                    "sentiment":
                    sentiment
                })
            return True
        except:
            print('ERROR could not load tweet')
            return True
Example #25
0
    # suit1.addTest(TestRequests("test_get_sou_ye"))
    suit1.addTests(
        [TestRequests("test_get_sou_ye"),
         TestRequests("test_get_text")])

    # 创建目录
    test_reult = os.path.join(os.getcwd(), "Results")
    # 创建文件
    now = time.strftime('%Y-%m-%d %H-%M-%S')
    file_name = test_reult + "\\" + now + "result.html"

    with open(file_name, 'wb') as f:
        runner = HTMLTestRunner(stream=f,
                                title="标题描述",
                                description="1.使用了那个接口 2.接口注意事项")
        runner.run(suit1)


def test_loader():
    print(os.getcwd())
    test_dir = os.getcwd() + "/testCase"
    print(test_dir)
    driver = unittest.defaultTestLoader.discover(test_dir, pattern="test*.py")
    runner2 = unittest.TextTestRunner()
    runner2.run(driver)


if __name__ == "__main__":
    test_single_test()
    sendemail.send_email()
Example #26
0
from bs4 import BeautifulSoup
import requests
import config
import sendemail

##      get everything
source = requests.get(config.target_url).text
##      get the source code
soup = BeautifulSoup(source, "html.parser")
##      get note from thehtml
note = soup.find(class_=config.divid).get_text()

if "alo" in note:
    print('closed')

else:
    sendemail.send_email(sendemail.subject, sendemail.msg)
Example #27
0
import os
from xml.dom import minidom

from sendemail import send_email


os.system('python http_checker.py')

reports_dir = 'test-reports' # path to your log directory

reports = sorted([ f for f in os.listdir(reports_dir)])

print "Last test report = %s" % (reports[-1],)

xmldoc = minidom.parse(reports_dir + "/" + reports[-1])
testsuites = xmldoc.getElementsByTagName('testsuite')
# print len(testsuites)
errors_count = int(testsuites[0].attributes['errors'].value)
failures_count = int(testsuites[0].attributes['failures'].value)

if errors_count == 0 and failures_count == 0:
    send_email(reports_dir + "/" + reports[-1], "[Test Report]All tests passed!")
else:
    send_email(reports_dir + "/" + reports[-1], "[Test Report]Test run failed!")
Example #28
0
            f.write('') 
        

        strcu_time = time.strptime(date_to, '%Y-%m-%d')
        sun = datetime(strcu_time[0], strcu_time[1], strcu_time[2]) + timedelta(-1)  
        sun_str = sun.strftime("%Y-%m-%d")
        
        strcu_time = time.strptime(sun_str, '%Y-%m-%d')
        sat = datetime(strcu_time[0], strcu_time[1], strcu_time[2]) + timedelta(-1)  
        sat_str = sat.strftime("%Y-%m-%d")
        main(sat_str)
        time.sleep(2)        
        main(sun_str)
        time.sleep(2)
        
    main(date_to)    
    #Write_error(date_to)     
    return week
 
    

    

if __name__ == '__main__' :     
    week = Sleep_By_Day()   
    if t3_error >= 1:
        send_email('*****@*****.**','D:\\data\\myself\\test')        
        #send_email('*****@*****.**','D:\\data\\myself\\test')  


Example #29
0
def get_match_pairs():
    allUsers = db_helpers.getFromDatabase()
    all_ids = allUsers.keys()

    # Shuffle the list of all user ids
    random.shuffle(all_ids)

    # Make a list to store ones who are already matched
    already_matched = []

    print "All Ids", all_ids

    # odd case
    if len(all_ids) % 2:

        # First match 3 people who haven't met
        p1 = all_ids.pop()
        p1_dont_match = allUsers[p1]['already_met'].split(',')
        p1_ok = [item for item in all_ids if item not in p1_dont_match]

        p2 = p1_ok[random.randint(0, len(p1_ok) - 1)]
        p2_dont_match = allUsers[p2]['already_met'].split(',')
        p2_ok = [item for item in all_ids if item not in p2_dont_match]

        p1_p2_ok = [item for item in p1_ok if item in p2_ok]
        p3 = p1_p2_ok[random.randint(0, len(p1_p2_ok) - 1)]

        # Update each dontmatch
        p1_dont_match.append(p2)
        p1_dont_match.append(p3)

        p2_dont_match.append(p1)
        p2_dont_match.append(p3)

        p3_dont_match = allUsers[p3]['already_met'].split(',')
        p3_dont_match.append(p1)
        p3_dont_match.append(p2)

        db_helpers.updateDatabase(p1, p1_dont_match)
        db_helpers.updateDatabase(p2, p2_dont_match)
        db_helpers.updateDatabase(p3, p3_dont_match)

        all_ids.remove(p2)
        all_ids.remove(p3)

        platform = ''
        p1_plat = [
            int(allUsers[p1]['check_fb']),
            int(allUsers[p1]['check_ig']),
            int(allUsers[p1]['check_wa'])
        ]
        p2_plat = [
            int(allUsers[p2]['check_fb']),
            int(allUsers[p2]['check_ig']),
            int(allUsers[p2]['check_wa'])
        ]
        p3_plat = [
            int(allUsers[p3]['check_fb']),
            int(allUsers[p3]['check_ig']),
            int(allUsers[p3]['check_wa'])
        ]

        platList = []
        for i in range(3):
            if p1_plat[i] and p2_plat[i] and p3_plat:
                platList.append(platforms[i])

        if platList:
            platform = ", or " + ", ".join(platList)

        # Email
        msg = message3.format(fname1=allUsers[p1]['full_name'],
                              fname2=allUsers[p2]['full_name'],
                              fname3=allUsers[p3]['full_name'],
                              platforms=platform,
                              pname1=allUsers[p1]['pref_name'],
                              things1=allUsers[p1]['3_things'],
                              pname2=allUsers[p2]['pref_name'],
                              things2=allUsers[p2]['3_things'],
                              pname3=allUsers[p3]['pref_name'],
                              things3=allUsers[p3]['3_things'])
        # print(msg)
        sendemail.send_email([p1, p2, p3], subject, msg)

    # Iterate over all the ids
    for person in all_ids:

        # Skip current iteration if person already present
        if person in already_matched:
            continue

        # Get the ids you shouldn't match to, then construct a list of valid ids to match with
        p1_dont_match = allUsers[person]['already_met'].split(',')
        match_ok = []
        match_ok = [item for item in all_ids if item not in p1_dont_match]
        match_ok = [item for item in match_ok if item not in already_matched]

        # Pick the first person from the valid list, add both to the list of already matched people
        second_person = match_ok[0]
        already_matched.append(person)
        already_matched.append(second_person)

        # Update the database to update each user's already met list
        p2_dont_match = allUsers[second_person]['already_met'].split(',')

        # Update each user's dontmatch list to not repeat matching
        p2_dont_match.append(person)
        p1_dont_match.append(second_person)

        db_helpers.updateDatabase(person, p1_dont_match)
        db_helpers.updateDatabase(second_person, p2_dont_match)

        platform = ''
        p1_plat = [
            int(allUsers[person]['check_fb']),
            int(allUsers[person]['check_ig']),
            int(allUsers[person]['check_wa'])
        ]
        p2_plat = [
            int(allUsers[second_person]['check_fb']),
            int(allUsers[second_person]['check_ig']),
            int(allUsers[second_person]['check_wa'])
        ]

        platList = []
        for i in range(3):
            if p1_plat[i] and p2_plat[i]:
                platList.append(platforms[i])

        if platList:
            platform = ", or " + ", ".join(platList)

        # Fire Email function here
        msg = message2.format(fname1=allUsers[person]['full_name'],
                              fname2=allUsers[second_person]['full_name'],
                              platforms=platform,
                              pname1=allUsers[person]['pref_name'],
                              things1=allUsers[person]['3_things'],
                              pname2=allUsers[second_person]['pref_name'],
                              things2=allUsers[second_person]['3_things'])

        # print(msg)
        sendemail.send_email([person, second_person], subject, msg)
Example #30
0
        return f.read()


if __name__ == "__main__":
    for site in args.sites:
        logger.debug(site)
        sitem = getattr(sys.modules[__name__], site)
        if args.scrape:
            scraper = getattr(sitem, "scraper")
            html = scraper.scrape(config.min_rooms, config.max_rooms,
                                  config.max_rent, config.wbs)
        else:
            scraper = None
            html = get_sample(site)

        parser = getattr(sitem, "parser")
        flats = parser.parse(html)

        jsonfile = JsonFile.open(config.jsonfile)
        jsonfile.add_list(flats)

        newflats = jsonfile.new_items[:]

        if jsonfile.new_item_count > 0:
            logging.info("Found {} new flats".format(jsonfile.new_item_count))

        jsonfile.save()

        if args.email and len(newflats) > 0:
            sendemail.send_email(newflats, args.email)
result_shanghai = pd_shanghaimainold.drop_duplicates(keep=False)
result_shanghai = result_shanghai.drop_duplicates('companyCode', keep='last')
dfsize_shanghai = len(result_shanghai)
num = 0
for i in range(0, dfsize_shanghai):
    msg += str(result_shanghai.iloc[i]['companyCode'])
    msg += ':'
    msg += result_shanghai.iloc[i]['companyAbbr']
    msg += '\n'
    msg += '首次预约时间:'
    msg += result_shanghai.iloc[i]['publishDate0']
    msg += '\n'
    msg += '第一次变更时间:'
    msg += result_shanghai.iloc[i]['publishDate1']
    msg += '\n'
    msg += '第二次变更时间:'
    msg += result_shanghai.iloc[i]['publishDate2']
    msg += '\n'
    msg += '第三次变更时间:'
    msg += result_shanghai.iloc[i]['publishDate3']
    msg += '\n'
    msg += '\n'
    num += 1

import sendemail
if msg == '':
    msg = '年报预约时间没有变更'
print(msg)
sendemail.send_email(msg)
Example #32
0
def index_roller_auto():
    Datalog.write_log('Line706 自动模式启动')
    loop_cal = 1  #计算累计循环次数
    while (True):
        unix = time.time()
        system_date_ymdhms_string = str(
            datetime.datetime.fromtimestamp(unix).strftime(
                '%Y-%m-%d %H:%M:%S'))  # 获取系统时间
        system_date_ymd_string = str(
            datetime.datetime.fromtimestamp(unix).strftime(
                '%Y-%m-%d'))  # 获取系统时间日期
        system_time_hms_string = str(
            datetime.datetime.fromtimestamp(unix).strftime(
                '%H:%M:%S'))  # 获取系统时间分钟秒时间
        # 获取网络数据,间隔2秒
        #TODO 修改循环时间
        time_loop = 2
        time.sleep(time_loop)  # 间隔2秒执行
        #print('Line696 进入While循环次数:', loop_cal)
        loop_cal = loop_cal + 1
        sina_data_dict = get_db_network_data()  # 获取网络数据,返回list格式
        if (sina_data_dict == ''):
            print(system_date_ymdhms_string, ' Network error')
            Datalog.write_log(
                str(system_date_ymdhms_string) + ' Network error')
        else:  # 网络正常,执行程序
            price_now_510050 = sina_data_dict.get('510050').get('now')
            price_date_510050 = sina_data_dict.get('510050').get('date')
            price_time_510050 = sina_data_dict.get('510050').get('time')
            price_now_159915 = sina_data_dict.get('159915').get('now')
            price_date_159915 = sina_data_dict.get('159915').get('date')
            price_time_159915 = sina_data_dict.get('159915').get('time')
            price_now_150023 = sina_data_dict.get('150023').get('now')
            price_date_150023 = sina_data_dict.get('150023').get('date')
            price_time_150023 = sina_data_dict.get('150023').get('time')
            time_netwowk_hm = price_time_510050[0:5]
            time_netwowk_ms = price_time_510050[4:8]
            network_list = [(510050, price_now_510050, price_date_510050,
                             price_time_510050),
                            (159915, price_now_159915, price_date_159915,
                             price_time_159915),
                            (150023, price_now_150023, price_date_150023,
                             price_time_150023)]
            # 判断数据时间是否可录入
            print('Line568 ', system_date_ymdhms_string, ' 网络数据如下',
                  network_list)  # 分钟
            Datalog.write_log('网络数据:' + str(network_list))
            time_isOK = False
            time_isOK = if_time_is_ok(time_netwowk_hm, time_netwowk_ms)
            #print('time_isOK = ',time_isOK)
            if (time_isOK == True):  # 网络时间OK,数据可以考虑录入# 获取数据库数据
                #print('开始读取数据库数据')
                db_list_old = data_read_from_db()  # class:list
                #print('Line592 网络数据如下:',network_list)
                db_list_new = get_new_db_data(db_list_old,
                                              network_list)  # 新的数据,可以写入数据库
                clear_database()  # 清空数据库
                Datalog.write_log('Line596 数据库清空完成')
                Datalog.write_log('Line597 开始写入新数据到数据库')
                for i in range(0, 198):
                    if (db_list_new[i] != 0):
                        list_dic_key = [
                            'ID', 'Code', 'Price', 'Date', 'Time', 'KEMA',
                            'SEMA', 'LEMA', 'DIF', 'xlA', 'xlB', 'xlC',
                            'IsHold', 'KEMAH', 'PriceH', 'DEA', 'BuyToday'
                        ]
                        list_dic_value = list(db_list_new[i])
                        list_dic = dict(zip(list_dic_key, list_dic_value))
                        data_insert(list_dic)
                    else:
                        break
                Datalog.write_log('Line601 新数据写入数据库完成')
                # 是否进行交易
                Datalog.write_log('Line604 开始判断是否交易')

                def get_new_dict(i):  # 获取指定ID在数据库中的数据
                    list_dic_key = [
                        'ID', 'Code', 'Price', 'Date', 'Time', 'KEMA', 'SEMA',
                        'LEMA', 'DIF', 'xlA', 'xlB', 'xlC', 'IsHold', 'KEMAH',
                        'PriceH', 'DEA', 'BuyToday'
                    ]
                    list_dic_value = list(db_list_new[i])
                    list_dic = dict(zip(list_dic_key, list_dic_value))
                    return list_dic

                dic_510050 = get_new_dict(0)
                dic_159915 = get_new_dict(1)
                dic_150023 = get_new_dict(2)
                dic_510050_lst = get_new_dict(3)
                dic_159915_lst = get_new_dict(4)
                dic_150023_lst = get_new_dict(5)
                #print(dic_510050)
                #print(dic_159915)
                #print(dic_150023)
                #print(dic_510050_lst)
                #print(dic_159915_lst)
                #print(dic_150023_lst)
                buy_today = dic_510050.get('BuyToday')

                def get_dea_high_now():  # 计算DEA今日斜率最高的指数
                    DEAH = 0
                    DEAH_CODE = 0
                    DEAH_ID = 0
                    DEA_510050 = dic_510050.get('DEA')
                    DEA_159915 = dic_159915.get('DEA')
                    DEA_150023 = dic_150023.get('DEA')
                    if (DEA_510050 >= max(DEA_159915, DEA_150023)):
                        DEAH = DEA_510050
                        DEAH_CODE = 510050
                        DEAH_ID = 1
                    elif (DEA_159915 >= DEA_150023):
                        DEAH = DEA_159915
                        DEAH_CODE = 159915
                        DEAH_ID = 2
                    else:
                        DEAH = DEA_150023
                        DEAH_CODE = 150023
                        DEAH_ID = 3
                    result = dict(DEAH=DEAH,
                                  DEAH_CODE=DEAH_CODE,
                                  DEAH_ID=DEAH_ID,
                                  DEA_510050=DEA_510050,
                                  DEA_159915=DEA_159915,
                                  DEA_150023=DEA_150023)
                    return result

                def get_hold_lst():
                    Hold_DEA_Lst = 0
                    Hold_Code_Lst = 0
                    Hold_ID_Lst = 0
                    if (dic_510050_lst.get('IsHold') == 1):
                        Hold_DEA_Lst = dic_510050_lst.get('DEA')
                        Hold_Code_Lst = 510050
                        Hold_ID_Lst = 1
                    elif (dic_159915_lst.get('IsHold') == 1):
                        Hold_DEA_Lst = dic_159915_lst.get('DEA')
                        Hold_Code_Lst = 159915
                        Hold_ID_Lst = 2
                    elif (dic_150023_lst.get('IsHold') == 1):
                        Hold_DEA_Lst = dic_150023_lst.get('DEA')
                        Hold_Code_Lst = 150023
                        Hold_ID_Lst = 3
                    else:
                        Hold_DEA_Lst = 0
                        Hold_Code_Lst = 0
                        Hold_ID_Lst = 0
                    result = dict(HOLD_DEA=Hold_DEA_Lst,
                                  HOLD_CODE=Hold_Code_Lst,
                                  HOLD_ID=Hold_ID_Lst)
                    return result

                get_dea_high_n = get_dea_high_now()
                DEAH_NOW = get_dea_high_n.get('DEAH')
                DEAH_CODE_NOW = int(get_dea_high_n.get('DEAH_CODE'))
                DEAH_ID_NOW = int(get_dea_high_n.get('DEAH_ID'))
                get_hold = get_hold_lst()
                Hold_DEA = get_hold.get('HOLD_DEA')  # 昨日持仓代码的昨日DEA数值
                Hold_Code = int(get_hold.get('HOLD_CODE'))  # 昨日持仓代码
                Hold_ID = int(get_hold.get('HOLD_ID'))
                if Hold_Code == 510050:
                    Hold_DEA_Lst = get_dea_high_n.get(
                        'DEA_510050')  # 昨日持仓代码的现在DEA数值
                    Hold_Code_Lst = 510050
                    Hold_ID_Lst = 1
                elif Hold_Code == 159915:
                    Hold_DEA_Lst = get_dea_high_n.get(
                        'DEA_159915')  # 昨日持仓代码的现在DEA数值
                    Hold_Code_Lst = 159915
                    Hold_ID_Lst = 2
                elif Hold_Code == 150023:
                    Hold_DEA_Lst = get_dea_high_n.get(
                        'DEA_150023')  # 昨日持仓代码的现在DEA数值
                    Hold_Code_Lst = 150023
                    Hold_ID_Lst = 3
                else:
                    Hold_DEA_Lst = 0  # 昨日持仓代码的现在DEA数值
                    Hold_Code_Lst = 0
                    Hold_ID_Lst = 0
                print('DEAH_NOW=', DEAH_NOW, ' DEAH_CODE=', DEAH_CODE_NOW)
                print('Hold_DEA_Lst=', Hold_DEA_Lst, ' Hold_Code_Lst=',
                      Hold_Code_Lst)
                print('DEAH_NOW - Hold_DEA_Lst=', DEAH_NOW - Hold_DEA_Lst)
                if (buy_today == 1):
                    print('Line618 交易额度有余,可以进行交易')
                    Datalog.write_log('交易额度有余,可以进行交易')
                    if (Hold_Code_Lst == 0):  # 昨日空仓
                        if (DEAH_NOW < 0.000006):
                            print('未达到建仓标准,保持空仓')
                            Datalog.write_log('未达到建仓标准,保持空仓')
                        else:
                            print('建仓,持有指数:', DEAH_CODE_NOW)
                            Datalog.write_log('建仓,持有指数:' + str(DEAH_CODE_NOW))
                            cmd_text = 'UPDATE data_table SET IsHold = 1 WHERE ID=' + str(
                                DEAH_ID_NOW)
                            update_db(cmd_text)
                            cmd_text = 'UPDATE data_table SET BuyToday = 0 WHERE ID=1'
                            update_db(cmd_text)
                            cmd_text = 'UPDATE data_table SET BuyToday = 0 WHERE ID=2'
                            update_db(cmd_text)
                            cmd_text = 'UPDATE data_table SET BuyToday = 0 WHERE ID=3'
                            update_db(cmd_text)
                            #ht_hold_stock(DEAH_CODE_NOW)
                            sendemail.send_email(DEAH_CODE_NOW)
                    else:  # 昨日持仓
                        if DEAH_NOW < 0.000006:  # 空仓
                            print('空仓,卖出持有指数')
                            Datalog.write_log('空仓,卖出持有指数')
                            cmd_text = 'UPDATE data_table SET BuyToday = 1 WHERE ID=1'
                            update_db(cmd_text)
                            cmd_text = 'UPDATE data_table SET BuyToday = 1 WHERE ID=2'
                            update_db(cmd_text)
                            cmd_text = 'UPDATE data_table SET BuyToday = 1 WHERE ID=3'
                            update_db(cmd_text)
                            #ht_hold_stock(0)
                            sendemail.send_email(0)
                        else:
                            #print('DEAH_NOW=', DEAH_NOW)
                            #print('Hold_DEA_Lst=', Hold_DEA_Lst)
                            #print('DEAH_NOW - Hold_DEA_Lst=', DEAH_NOW - Hold_DEA_Lst)
                            if DEAH_NOW - Hold_DEA_Lst >= 0.00015:
                                print('换仓至指数:', DEAH_CODE_NOW)
                                Datalog.write_log('换仓至指数:' +
                                                  str(DEAH_CODE_NOW))
                                cmd_text = 'UPDATE data_table SET IsHold = 1 WHERE ID=' + str(
                                    DEAH_ID_NOW)
                                update_db(cmd_text)
                                cmd_text = 'UPDATE data_table SET BuyToday = 0 WHERE ID=1'
                                update_db(cmd_text)
                                cmd_text = 'UPDATE data_table SET BuyToday = 0 WHERE ID=2'
                                update_db(cmd_text)
                                cmd_text = 'UPDATE data_table SET BuyToday = 0 WHERE ID=3'
                                update_db(cmd_text)
                                #ht_hold_stock(DEAH_CODE_NOW)
                                sendemail.send_email(DEAH_CODE_NOW)
                            else:
                                print('未达到切换标准,继续持有指数:', Hold_Code_Lst)
                                Datalog.write_log('未达到切换标准,继续持有指数:' +
                                                  str(Hold_Code_Lst))
                                cmd_text = 'UPDATE data_table SET IsHold = 1 WHERE ID=' + str(
                                    Hold_ID_Lst)
                                update_db(cmd_text)
                else:
                    #print('DEAH=', DEAH_NOW, 'DEAH Code=', DEAH_CODE_NOW, 'DEAH ID=', DEAH_ID_NOW)
                    #print('Hold DEA=', Hold_DEA_Lst, 'Hold Code=', Hold_Code_Lst, 'Hold ID=', Hold_ID_Lst)
                    print('交易额度不足,今日不交易,继续持有指数:', Hold_Code_Lst)
                    Datalog.write_log('交易额度不足,今日不交易,继续持有指数:' +
                                      str(Hold_Code_Lst))
                    cmd_text = 'UPDATE data_table SET IsHold = 1 WHERE ID=' + str(
                        Hold_ID_Lst)
                    update_db(cmd_text)
Example #33
0
# 用例执行总入口
import unittest
import HTMLTestReportCN
# import HTMLTestRunner
import time
import sendemail
import configread

discover = unittest.defaultTestLoader.discover(configread.prjdir,
                                               pattern='test*.py')

now = time.strftime('%Y-%m-%d %H-%M-%S')
report_path = configread.prjdir + '\\report\\' + now + 'UIAutoReport.html'
with open(report_path, 'wb') as fp:
    runner = HTMLTestReportCN.HTMLTestRunner(
        stream=fp,
        title=u'自动化测试报告',
        description=u'环境:夜神安卓模拟器4.4.2',
        tester=u"于淼然",
    )
    runner.run(discover)
report_path = sendemail.get_report(configread.prjdir + '\\report')
sendemail.send_email(report_path)
Example #34
0
def email_fail():
    import sendemail
    recipient = ["*****@*****.**"]
    text = 'not today'
    html = "not today, price is still over 49.9"
    sendemail.send_email(recipient, text, html)
Example #35
0
def test():
    language = request.form['language']
    algorithm = request.form['algorithm']
    shape = request.form['Word']
    f = request.files["file1"]
    dataset = request.files["file2"]
    if current_user.is_authenticated:
        usernameee = current_user.username
        isAuthenticated = 'yes'
    else:
        usernameee = "guest"
        isAuthenticated = 'no'
    f.save(os.path.join("uploads",usernameee+"-"+f.filename))
    f.save(os.path.join("static/texts",usernameee+"-"+f.filename))

    
    word_cloud.cloudify(usernameee+"-"+f.filename, shape)
    
    outname = usernameee+"-"+f.filename+"_out.png"
    pic1 = os.path.join(app.config['UPLOAD_FOLDER'], outname)
    file1 = open("uploads/"+usernameee+"-"+f.filename, 'r', encoding='utf-8')
    text = file1.read()
    if language == 'english' and algorithm == 'naivebayes':
       
        sentences = nltk.tokenize.sent_tokenize(text)
        topics =[]
        dominant_topic = naivebayes.predict_category(text)
        for i in range(len(sentences)):
            topics.append(naivebayes.predict_category(sentences[i]))

        topics = set(topics)

        workbook = xlwt.Workbook()
        sheet = workbook.add_sheet("results")
        i=0
        for value in topics:
            sheet.write(i,0,i )
            sheet.write(i,1, value)
            i = i+1        
        workbook.save("static/excelfiles/"+usernameee+"-"+f.filename+".xls")
        name = usernameee+"-"+f.filename+".xls"
        excelfile = os.path.join(app.config['EXCEL_FILES'], name)
        if current_user.is_authenticated:
            sendemail.send_email(pic1,excelfile, current_user.email)

        return render_template("resultpage.html", img_file =pic1, algorithm = 'naivebayes', tpcs = topics, dominant = dominant_topic, excelfile =excelfile)
    elif language == 'turkish' and algorithm == 'lda':
        
        stopwords = request.files['file3']
        if stopwords.filename != "":
            choice = True
            stopwords.save(os.path.join("uploads",usernameee+"-"+stopwords.filename))
        else:
            choice = False
        if  request.form['ngram'] == 'True':
            ngram_choice = True
            ngram_num = int(request.form['number'])
        else:
            ngram_choice = False  

        results = lda_70.lda_70(text,ngram_num,ngram_choice, choice, "uploads/"+usernameee+"-"+stopwords.filename)
        workbook = xlwt.Workbook()
        sheet = workbook.add_sheet("results")
        i=1
        sheet.write(0,0,'Score')
        sheet.write(0,1,'Topic Vocabulary')
        for value in results:
            sheet.write(i,0, value.topic)
            sheet.write(i,1,value.score)
            i=i+1

        workbook.save("static/excelfiles/"+usernameee+"-"+f.filename+".xls")
        name = usernameee+"-"+f.filename+".xls"
        excelfile = os.path.join(app.config['EXCEL_FILES'], name)
        if current_user.is_authenticated:
            sendemail.send_email(pic1,excelfile, current_user.email)

        return render_template("resultpage.html", img_file = pic1, algorithm = "lda", tpcs = results, excelfile = excelfile)
    
    elif language == 'english' and algorithm == 'nmf':
        results = nmf_ready_to_use.nmf_algorithm(text, int(request.form['number']))
        workbook = xlwt.Workbook()
        sheet = workbook.add_sheet("results")
        i=1
        sheet.write(0,0,'Topic Vocabulary')
        sheet.write(0,1,'Accuracy Score')
        for value in results:
            sheet.write(i,0, value.topic)
            sheet.write(i,1,value.score)
            i=i+1

        workbook.save("static/excelfiles/"+usernameee+"-"+f.filename+".xls")
        name = usernameee+"-"+f.filename+".xls"
        excelfile = os.path.join(app.config['EXCEL_FILES'], name)
        if current_user.is_authenticated:
            sendemail.send_email(pic1,excelfile, current_user.email)


        return render_template("resultpage.html",img_file =pic1, algorithm = "nmf", tpcs = results , excelfile = excelfile)
    elif language == 'english' and algorithm == 'pam':
        results = pam_eng.pam_english("uploads/"+usernameee+"-"+f.filename)
        workbook = xlwt.Workbook()
        
        sheet = workbook.add_sheet("results")
        i=1
        sheet.write(0,0,'Topic')
        sheet.write(0,1,'Sub Topics')
        sheet.write(0,2,'Accuracy Score')

        for value in results:
            sheet.write(i,0, value['topic'])
            
            sheet.write(i,1,str(value['subs']))
            sheet.write(i,2,value['prob'])
            i=i+1

        workbook.save("static/excelfiles/"+usernameee+"-"+f.filename+".xls")
        name = usernameee+"-"+f.filename+".xls"
        excelfile = os.path.join(app.config['EXCEL_FILES'], name)
        if current_user.is_authenticated:
            sendemail.send_email(pic1,excelfile, current_user.email)

        return render_template("resultpage.html",img_file =pic1, algorithm = "pam", tpcs = results, excelfile = excelfile)
    elif language == 'turkish' and dataset.filename != "" and request.form['algorithm']=='lda2':
        
        dataset.save(os.path.join("uploads",usernameee+"-"+dataset.filename))
        stopwords = request.files['file3']
        if stopwords.filename != "":
            choice = True
            stopwords.save(os.path.join("uploads",usernameee+"-"+stopwords.filename))
        else:
            choice = False
        if  request.form['ngram'] == 'True':
            ngram_choice = True
            ngram_num = int(request.form['number'])
        else:
            ngram_choice = False  
        
        freeze_support()
        Q = Queue()
        p1=Process(target=tr_lda_choice.f,args=("uploads/"+usernameee+"-"+dataset.filename, request.form['column'], choice, "uploads/"+usernameee+"-"+stopwords.filename, ngram_choice,ngram_num, "uploads/"+usernameee+"-"+f.filename,int(request.form['topic_number']), Q,))

        p1.start()
        p1.join()

        results = Q.get()
        

        return render_template("resultpage.html",img_file =pic1, algorithm = "lda", tpcs = results)

    elif language == 'english' and dataset.filename != "" and algorithm == "nmf2":
        dataset.save(os.path.join("uploads",usernameee+"-"+dataset.filename))
        stopwords = request.files['file3']
        if stopwords.filename != "":
            choice = True
            stopwords.save(os.path.join("uploads",usernameee+"-"+stopwords.filename))
        else:
            choice = False
        if  request.form['ngram'] == 'True':
            ngram_choice = True
            ngram_num = int(request.form['number'])
        else:
            ngram_choice = False  
        file3 = open("uploads/"+usernameee+"-"+stopwords.filename, 'r', encoding='utf-8')
        stopwordss = file3.read()
        results = nmf_with_user_data_en.nmf_with_dataset("uploads/"+usernameee+"-"+dataset.filename,request.form['column'], choice,stopwordss,ngram_num,text)
        return render_template("resultpage.html",img_file =pic1, algorithm = "nmf", tpcs = results )
    elif language == 'english' and dataset.filename != "" and algorithm == 'lda2':
        dataset.save(os.path.join("uploads",usernameee+"-"+dataset.filename))
        stopwords = request.files['file3']
        if stopwords.filename != "":
            choice = True
            stopwords.save(os.path.join("uploads",usernameee+"-"+stopwords.filename))
        else:
            choice = False
        if  request.form['ngram'] == 'True':
            ngram_choice = True
            ngram_num = int(request.form['number'])
        else:
            ngram_choice = False  
        
        freeze_support()
        Q = Queue()
        p1=Process(target=en_lda_choice.f,args=("uploads/"+usernameee+"-"+dataset.filename, request.form['column'], choice, "uploads/"+usernameee+"-"+stopwords.filename, ngram_choice,ngram_num, "uploads/"+usernameee+"-"+f.filename, int(request.form['topic_number']),Q,))
        p1.start()
        p1.join()

        results = Q.get()
        return render_template("resultpage.html",img_file =pic1, algorithm = "lda", tpcs = results)
    elif language == 'turkish' and dataset.filename != "" and algorithm == "nmf2":
        dataset.save(os.path.join("uploads",usernameee+"-"+dataset.filename))
        stopwords = request.files['file3']
        if stopwords.filename != "":
            choice = True
            stopwords.save(os.path.join("uploads",usernameee+"-"+stopwords.filename))
        else:
            choice = False
        if  request.form['ngram'] == 'True':
            ngram_choice = True
            ngram_num = int(request.form['number'])
        else:
            ngram_choice = False  
        file3 = open("uploads/"+usernameee+"-"+stopwords.filename, 'r', encoding='utf-8')
        stopwordss = file3.read()
        results = nmf_with_user_data_tr.nmf_with_dataset("uploads/"+usernameee+"-"+dataset.filename,request.form['column'], choice,stopwordss,ngram_num,text)
        return render_template("resultpage.html",img_file =pic1, algorithm = "nmf", tpcs = results )
    elif language == 'english' and algorithm == 'lda':
        results = lda_en_30_with_saved_model.lda(text)
        workbook = xlwt.Workbook()
        sheet = workbook.add_sheet("results")
        i=1
        sheet.write(0,0,'Score')
        sheet.write(0,1,'Topic Vocabulary')
        for value in results:
            sheet.write(i,0, value.topic)
            sheet.write(i,1,value.score)
            i=i+1

        workbook.save("static/excelfiles/"+usernameee+"-"+f.filename+".xls")
        name = usernameee+"-"+f.filename+".xls"
        excelfile = os.path.join(app.config['EXCEL_FILES'], name)
        if current_user.is_authenticated:
            sendemail.send_email(pic1,excelfile, current_user.email)

        return render_template("resultpage.html", img_file = pic1, algorithm = "lda", tpcs = results, excelfile = excelfile)