def handle_question(command):
    """
    columns: name, email, phone, committee, committeeRole, dayjob
    """
    create_db.create_db()

    if "whois" in command:
        result = get_answer.run_query(command, "who")
        answer = prepare_answer(result)
        return answer

    elif "getme" in command:
        result = get_answer.run_query(command, "get")
        if result:
            clean_result = [x for t in result for x in t]
            # format: name, email, phone, gender
            if clean_result[3] == "f":
                pronoun = "her"
            elif clean_result[3] == "m":
                pronoun = "him"
            answer = clean_result[0].title(
            ) + " can be reached at " + clean_result[1].lower(
            ) + " or " + clean_result[
                2] + ". Tell " + pronoun + " I said 'hello'."
            return answer
        else:
            return "Are you sure they exist?"
def main():

    genes_of_interest = input(
        "Enter the genes you want to look up, separated by a space: ")
    confirmation = input("You entered these genes: " +
                         genes_of_interest.strip() +
                         ". Is that right? Enter y/n: ")

    if confirmation == 'y':
        # Check if the database already exists
        print("Checking if databases exist...")
        if is_sqlite3('./data/mydb'):
            # If it does, ask if user wants to update it
            update_database = input(
                "Do you want to update your database before running analysis? Enter y/n: "
            )
            if update_database == 'y':
                # Do the updating
                print("Updating databases...")
                refresh_db()
        else:
            # Otherwise create the database
            print("Creating databases...")
            create_db()
        # Then run the analysis
        run_analysis(genes_of_interest)

    elif confirmation == "n":
        print('Exiting! Bye bye.')
Beispiel #3
0
def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        if os.path.isfile(DATABASE):
            db = g._database = sqlite3.connect(DATABASE)
        else:
            create_db.create_db(DATABASE)
    return db
Beispiel #4
0
def get_db():
    """ This function accesses the global database.
    If the database isn't loaded and doesn't exist, it will
    create one in the local directory. Note: when this is hosted
    on a real webserver, it might put the database in the home directory.
    """
    db = getattr(g, '_database', None)
    if db is None:
        if os.path.isfile(create_db.DATABASE):
            db = g._database = sqlite3.connect(create_db.DATABASE)
        else:
            create_db.create_db(create_db.DATABASE)
            db = g._database = sqlite3.connect(create_db.DATABASE)
    return db
Beispiel #5
0
def main():
    """ Main program wrapper """

    config_cdash.LOG = configure_cdash_log.configure_log(config_cdash.LOG_FILENAME, config_cdash.LOG_NAME,
                                                         config_cdash.LOG_LEVEL)
    global MPD_DICT
    global TH_CONN
    #global D_CONN
    global cursor
    config_cdash.LOG.info('Starting the cache in {} mode'.format(config_cdash.PREFETCH_SCHEME))
    if TH_CONN == None:
        TH_CONN = create_db.create_db(config_cdash.THROUGHPUT_DATABASE, config_cdash.THROUGHPUT_TABLES)
    #if D_CONN == None:
    #    D_CONN = create_db.create_db(config_cdash.DELTA_DATABASE, config_cdash.DELTA_TABLES)
    try:
        with open(config_cdash.MPD_DICT_JSON_FILE, 'rb') as infile:
            MPD_DICT = json.load(infile)
    except IOError:
        config_cdash.LOG.warning('Starting Cache for first time. Could not find any MPD_json file. ')
    # Starting the Cache Manager
    global cache_manager
    config_cdash.LOG.info('Starting the Cache Manager')
    cache_manager = CacheManager.CacheManager()
    # Function to start server
    http_server = BaseHTTPServer.HTTPServer((config_cdash.HOSTNAME, config_cdash.PORT_NUMBER),
                                            MyHTTPRequestHandler)
    config_cdash.LOG.info("Cache-Server listening on {}, port:{} - press ctrl-c to stop".format(config_cdash.HOSTNAME,
                                                                                            config_cdash.PORT_NUMBER))
    try:
        http_server.serve_forever()
    except KeyboardInterrupt:
        config_cdash.LOG.info('Terminating the Cache Manager')
        cache_manager.terminate()
        return
    def __init__(
            self,
            kafka_input_topic: str,
            number_of_cameras: int,
    ) -> None:
        self.kafka_input_topic = kafka_input_topic
        self.num_of_cams = int(number_of_cameras)
        self.kafka_helper = svt.kafka

        self.camera_handler_instance = Handlers.cam_handler()
        self.user_handler_instance = Handlers.user_handler()
        self.ann_handler_instance = Handlers.ann_handler()
        self.img_handler_instance = Handlers.img_handler()
        self.fb_handler_instance = Handlers.fb_handler()

        create_db(self.num_of_cams)
Beispiel #7
0
import os
import sys

sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from preference import preference
from create_table import create_table
from create_db import create_db

create_db(preference.db_name)
create_table(preference.db_name, preference.table_name)
Beispiel #8
0
def fetch(id):
    if request.method == "POST":
        text1=request.form['title']
        text2=request.form['details']
        entries = edit_entry(text1, text2, id=id)
        return redirect(url_for('index'))


    else:
        entries = fetch_entry(id)
        return render_template("edit.html", entries=entries)




@app.route('/search', methods=['GET','POST'])
def search():
    if request.method == 'POST':

        entries = search_entry(date1=request.form['search_date'])
        if not entries:
            flash('Sorry!! No journal entry is available for the date')
            return render_template('search_results.html')

        print('search results',entries)
        return render_template('search_results.html', entries=entries)


if __name__ == '__main__':
    create_db()
    app.run(port = 8000 ,debug=True)
Beispiel #9
0
 def setUp(self):
     self.db_fd = tempfile.mkstemp()
     create_db.create_db(self.db_fd[1])
     self.db = sqlite3.connect(self.db_fd[1])
Beispiel #10
0
def main(command=None):

    create_db.create_db()
    stocks_screener(command)
    sp.stock_key_data()
    sp.stock_profile()
Beispiel #11
0
    def data_from_db(self):
        """
        get subreddit corpus from database reddit.db

        :return:
        text_matrix: matrix of text in subreddits. rows are subreddits.
        sub_list: list of subreddits included in the matrix
        sub_to_index: dictionary for converting from subreddit name to index in the matrix
        """

        sub_list = []
        text_matrix = []
        unstemmed_text_matrix = []  # used for word cloud later

        connecting_to_db = True

        sql_command = "SELECT subreddit, GROUP_CONCAT(body, ' ') as all_comments FROM comments GROUP BY subreddit"

        while connecting_to_db:
            try:
                print("Connecting to DB.\n")
                pwd = os.getcwd()
                db_conn = sqlite3.connect(pwd + '/../db/reddit.db')
                c = db_conn.cursor()
                results = c.execute(sql_command)

            except sqlite3.OperationalError:
                print("Table does not exist yet. Creating from CSV.\n")
                create_db(db_conn)
                continue

            print("Done.")

            break

        english_stop_words = stopwords.words('english')

        r = praw.Reddit(user_agent='daniel_scraper')

        for i, row in enumerate(list(results)):
            print("Loading subreddit {}: {}....".format(i, row[0]), end="")

            '''
            try:
                if r.get_subreddit(row[0]).subscribers < 50000:
                    print("Done")
                    continue

            except:
                print("Something went wrong. Continuing.")
                continue
            '''

            sub_list.append(row[0].lower())
            text_matrix.append(process_text(row[1], punctuation, english_stop_words))

            unstemmed_text_matrix.append(process_text(row[1], punctuation, english_stop_words, stem=False))

            print("Done")

        sub_to_index = {sub_name: index for sub_name, index in zip(sub_list, range(len(sub_list)))}

        print("Done.\n")

        text_matrix = np.array(text_matrix)
        unstemmed_text_matrix = np.array(unstemmed_text_matrix)

        np.save('unstemmed_text_matrix.npy', unstemmed_text_matrix)
        np.save('text_matrix.npy', text_matrix)
        pickle.dump(sub_list, open("sub_list.p", "wb"))
        pickle.dump(sub_to_index, open("sub_to_index.p", "wb"))

        return text_matrix, sub_list, sub_to_index
# -*- coding: utf-8 -*-
"""
Задание 18.1a

Скопировать скрипт add_data.py из задания 18.1.

Добавить в файл add_data.py проверку на наличие БД:
* если файл БД есть, записать данные
* если файла БД нет, вывести сообщение, что БД нет и её необходимо сначала создать

"""

import sys
import glob
from create_db import create_db
from add_data import add_data
from add_data import add_switches
sys.path.insert(0, 'C:/Users/snowowl/PycharmProjects/Natenka_python_tasks/18_db/')

db_filename = 'dhcp_snooping.db'
schema_filename = 'dhcp_snooping_schema.sql'
dhcp_snoop_files = glob.glob('sw*_dhcp_snooping.txt')


create_db(db_filename, schema_filename)
add_data(dhcp_snoop_files, add_switches('switches.yml', dhcp_snoop_files))

Beispiel #13
0
На данном этапе, оба скрипта вызываются без аргументов.

'''


if __name__ == '__main__':
    from create_db import create_db
    from add_data import parse_dhcp_file
    from add_data import add_data
    from add_data import parse_yml_file
    import glob
    from pprint import pprint

    db_filename = 'dhcp_snooping.db'
    schema_filename = 'dhcp_snooping_schema.sql'
    db_connection = create_db(db_filename, schema_filename)
    #print(type(db_connection))

    dhcp_snoop_files = glob.glob('sw*_dhcp_snooping.txt')
    print('\nFiles found:')
    print(dhcp_snoop_files)

    dhcp_list = []

    for sw_file in dhcp_snoop_files:
        dhcp_list.extend(parse_dhcp_file(sw_file))

    print('\nParsing result:')
    pprint(dhcp_list)

    sw_list = parse_yml_file('switches.yml')
Beispiel #14
0
    def setUp(self):
        db_session.configure(bind=self.engine)
        db_session.remove()

        create_db(db_session)
Beispiel #15
0
def checkdb():
    if os.path.isfile('data/intlog.sqlite'):
        pass
    else:
        create_db.create_db()
 def setUp(self):
     self.client = app.test_client()
     with app.app_context():
         create_db(app.db)
    #                                   move_speed=0.05)

stop_demo = False
repeat = False
first = True

while (not stop_demo):

    if not repeat:

        # Delete possible existing and create a new database and open it
        try:
            os.remove(db_filename)
        except OSError:
            pass
        create_db(db_filename)

        connection = sqlite3.connect(db_filename)
        cursor = connection.cursor()

        # Record a sample in the database
        with pypot.dynamixel.DxlIO('/dev/ttyACM1') as dxl_io:
            no_success = True
            while no_success:
                try:

                    dxl_io.enable_torque([27, 29])

                    # open hand
                    dxl_io.set_goal_position({27: -180.00})
                    dxl_io.set_goal_position({29: -180.00})
Beispiel #18
0
 def clearplayers():
     #player.clear_players(GAME_ID, get_db())
     create_db.create_db()
     return ''
        record = [bank_bic, bank_name, None, None]
        manual.append(record)
    return manual

if __name__ == '__main__':
    manual_name = None
    db_name = None
    # Read arguments.
    if len(sys.argv) == 1:
        manual_name = 'Manual.txt'
        db_name = 'manual.db'
    elif len(sys.argv) == 2:
        manual_name = sys.argv[1]
        db_name = manual_name[:-3]
    elif len(sys.argv) == 3:
        manual_name = sys.argv[1]
        db_name = sys.argv[2]
    else:
        print 'Error. Invalid arguments count. Use "python \
update_banks_manual.py [input_file] [output_file]" syntax.'
        exit()

    if not os.path.exists(manual_name):
        print 'Error. File "' + manual_name + '" doesn\'t exist.'
        exit()
    manual = read_manual(manual_name)
    if manual != None:
        try:
            create_db(db_name, manual)
        except Exception,  x:
            print "Error: ", x
Beispiel #20
0
                            )
def main_message_callback(message):
    MyLoger.debug(
        f'message.from_user.id={message.from_user.id}|message.from_user.first_name={message.from_user.first_name}|message.from_user.username={message.from_user.username}'
    )
    try:
        bot.delete_message(message.message.chat.id, message.message.message_id)
    except:
        MyLoger.error(
            f"Error delete message! message.from_user.id={message.from_user.id}"
        )
    main_message(message)


# Хендлер для кнопки в головному меню (неактивни функціонал)
@bot.message_handler(func=lambda message: message.text == '🌐Выбрать язык🌐' or
                     message.text == 'Вибрати мову')
def chose_language(message):
    MyLoger.debug(
        f'message.from_user.id={message.from_user.id}|message.from_user.first_name={message.from_user.first_name}|message.from_user.username={message.from_user.username}'
    )
    bot.send_message(message.chat.id,
                     "Неактивний функціонал...",
                     reply_markup=False)


if __name__ == '__main__':
    create_db.create_db(db_name)
    MyLoger.debug('Bot start working...')
    bot.infinity_polling(none_stop=True)
Beispiel #21
0
    return 'Success'


def parameterized_query_user(conn, userid):
    c = conn.cursor()
    c.execute("SELECT * from users where userid = ?", (userid, ))
    results = c.fetchall()

    for r in results:
        print(r)

    return 'Success'


if __name__ == '__main__':

    dbfile = 'db/users.db'
    conn = create_db.create_db(dbfile)

    if not conn:
        print('Failed to connect to DB')
        exit()

    u = input('Enter username to login: '******'Password: '******'User {} successfully logged in'.format(u))
    else:
        print('Login Failed')
Beispiel #22
0
 def __init__(self, db_filename):
     create_db.create_db(db_filename)
     self.db_connection = sqlite3.connect(db_filename)
     self.db_cursor = self.db_connection.cursor()
Beispiel #23
0
def create():
    create_db()
    return 'criou'
Beispiel #24
0
 def setUp(self):
     """Setup tests."""
     create_db()
Beispiel #25
0
        target = args.edit
        if not args.search:
            searching = None
        else:
            searching = args.search
        edit_todo.edit_todo(searching, target)
    elif args.detail:
        if not args.search:
            detail.detail()
        else:
            detail.detail(args.search)
    elif args.remove:
        if not args.search:
            remove_todo.remove_todo()
        else:
            remove_todo.remove_todo(args.search)
    elif args.search:
        search.search(args.search)
    elif args.stat:
        stat_todo.stat_todo()
    else:
        print("Hello!, This is ACE TODO APPLICATION")
        print(
            "If you want to run action of ACE, confirm options(-h or --help)")
        print()


if __name__ == "__main__":
    create_db.create_db()
    run_program()
Beispiel #26
0
import login
import create_db

print('User Login Service')

conn = create_db.create_db()
if not conn:
    print('Failed to connect to DB')
    exit()

while True:
    level = input("""
Select Security Level: 
0 - No Security
1 - Blacklist Approach
2 - Whitelist Approach
3 - Parameterized Query
4+ - Exit
Choice: """)

    if not str(level).isnumeric():
        print('Invalid choice, Exiting!')
        break

    level = int(level)

    if level >= 4:
        break

    op = int(input('1 - Login\n2 - Query User\nChoice: '))