def __init__(self, username, password): """ Initializes a VerseBot object with supplied username and password. It is recommended that the username and password are stored in something like an environment variable for security reasons. """ logging.basicConfig(level=LOG_LEVEL) self.log = logging.getLogger("versebot") logging.getLogger("requests").setLevel(logging.WARNING) try: self.log.info("Connecting to reddit...") self.r = praw.Reddit(user_agent = ("VerseBot by /u/mgrieger. GitHub: https://github.com/matthieugrieger/versebot")) self.o = OAuth2Util.OAuth2Util(self.r) self.o.refresh(force=True) except Exception as err: self.log.critical("Exception: %s", err) self.log.critical("Connection to reddit failed. Exiting...") exit(1) self.log.info("Successfully connected to reddit!") self.log.info("Connecting to database...") database.connect(self.log) # Initialize connection to database. self.log.info("Successfully connected to database!") self.parser = WebParser() # Initialize web parser with updated translation list. self.log.info("Updating translation list table...") database.update_translation_list(self.parser.translations) self.log.info("Translation list update successful!") self.log.info("Cleaning old user translation entries...") database.clean_user_translations() self.log.info("User translation cleaning successful!")
def wrapper(*args, **kwargs): passthrough = False passthroughExtensions = (".html", ".xml", "txt") passthroughPaths = ("/resources", "/views", "/static", "/theme/static") test1 = [ext for ext in passthroughExtensions if ext in request.path] test2 = [p for p in passthroughPaths if request.path.startswith(p)] passthrough = (len(test1) > 0 or len(test2) > 0) # # Connect to our database # if len(config.ENVIRONMENT["DB_HOST"]): database.connect( engine = "mysql", host = config.ENVIRONMENT["DB_HOST"], port = config.ENVIRONMENT["DB_PORT"], database = config.ENVIRONMENT["DB_NAME"], user = config.ENVIRONMENT["DB_USER"], password = config.ENVIRONMENT["DB_PASSWORD"] ) # # Get the current theme and add framework paths # if installservice.isEngineInstalled(): request.themeName = themeservice.getThemeName() themeservice.addThemeToTemplatePath(themeName=request.themeName) if not passthrough: if not installservice.isEngineInstalled() and not request.path.startswith("/install"): redirect("/install") # # Setup session and environment stuff # request.session = request.environ.get("beaker.session") request.all = dict(list(request.query.items()) + list(request.forms.items())) if installservice.isEngineInstalled(): request.timezone = engineservice.getBlogTimezone() config.TIMEZONE = request.timezone else: config.TIMEZONE = "UTC" # # Finally call the the next method in the chain # body = callback(*args, **kwargs) database.disconnect() return body else: body = callback(*args, **kwargs) database.disconnect() return body
def setup(self): database_create(k_database) database.connect(k_database) system = User(0) self.room_id = Room.create("Test Room", system) self.room_controller = RoomController(self.room_id)
def test_bible_gateway_text_retrieval(self): """ Tests the retrieval of BibleGateway verse contents. """ parser = webparser.WebParser() database.connect(logging.getLogger("versebot")) v = verse.Verse("Genesis", "1", "esv", "mgrieger", "VerseBot", verse="1") self.assertTrue("In the beginning, God created the heavens and the earth." in parser.get_bible_gateway_verse(v)[0])
def init(): global config config=multiconfig.getConfig(configName, os.path.join(configDir, "base.yaml")) testing_config=os.path.join(configDir, "testing_config.yml") if os.path.exists(testing_config): config.load(testing_config) database.connect()
def test_database_overwrite(self): # Create empty file with open(k_database, 'w'): pass database_create(k_database) database.connect(k_database) assert os.path.exists(k_database)
def DBChoices(self, attr): import database as DB DB.initialize() DB.connect() try: return [(x.path, os.path.basename(x.path)) for x in DB.VideoBumpers.select().where(DB.VideoBumpers.type == self.vtype)] finally: DB.close()
def do_login(): # Reconnect if we timed out database.connect(main.data) if database.authenticate(request.form['username'], request.form['password']): session['logged_in'] = True return home() return render_template('/login.html', msg="Incorrect username or password.")
def test_bible_gateway_text_retrieval(self): """ Tests the retrieval of BibleGateway verse contents. """ parser = webparser database.connect(logging.getLogger("versebot")) v = verse.Verse("Genesis", "1", "esv", "mgrieger", "VerseBot", verse="1") self.assertTrue("In the beginning, God created " "the heavens and the earth." in parser.get_bible_gateway_verse(v)[0])
def run(self): database.connect() dbconnection = database.get_dbconnection() cursor = dbconnection.cursor() while True: if osp.exists('../stop_daemons'): self.log.printf(NORMAL, "Stop deamons file found.\n") sys.exit() try: dbconnection.commit() app = database.Apps.find1(name=self.appname) num_unsent = database.Results.count( app=app, server_state=RESULT_SERVER_STATE_UNSENT) if num_unsent < self.args['cushion'][0]: num_create = self.args['cushion'][0] - num_unsent self.log.printf(NORMAL, "%i unsent results. Creating %i more.\n", num_unsent, num_create) self.make_jobs( num=min(self.args['max_jobs_create'], num_create)) # wait for transitioner to create jobs now = int(time()) while True: self.log.printf(DEBUG, "Waiting for transitioner...\n") dbconnection.commit() cursor.execute( "select min(transition_time) as t from workunit") if cursor.fetchone()['t'] > now: break sleep(1) self.log.printf(DEBUG, "Created.\n") continue else: self.log.printf(DEBUG, "%i unsent results.\n", num_unsent) except CheckOutputError: pass except Exception as e: self.log.printf(CRITICAL, "Error: %s\n", str(e)) traceback.print_exception(type(e), e, sys.exc_info()[2], None, sys.stderr) sys.exit() sleep(int(self.args['sleep_interval'][0]))
def rescan(): scanner = Scanner() scanner.existing_tracks = Track.indexByPath(Track().getAllByPath( root_dir, '')) database.drop() database.connect() Track().create_table() Folder().create_table() scanner.parse(root_dir)
def DBChoices(attr): import database as DB DB.initialize() ratingSystem = util.getSettingDefault('rating.system.default') DB.connect() try: return [ (x.style, x.style) for x in DB.RatingsBumpers.select(DB.fn.Distinct(DB.RatingsBumpers.style)).where(DB.RatingsBumpers.system == ratingSystem) ] finally: DB.close()
def DBChoices(attr): import database as DB DB.initialize() ratingSystem = util.getSettingDefault('rating.system.default') DB.connect() try: return [(x.style, x.style) for x in DB.RatingsBumpers.select( DB.fn.Distinct(DB.RatingsBumpers.style)).where( DB.RatingsBumpers.system == ratingSystem)] finally: DB.close()
def send_mails_to_users(data, date): data = cleanmail(data) try: conn, cursor = connect() cursor.execute("select * from mails") result = cursor.fetchall() conn.close() except (MySQLdb.Error, MySQLdb.Warning) as e: conn.close() return all_mails = [x[0] for x in result] conn, cursor = connect() query = "select * from accepted_users" cursor.execute(query) accepted_users = cursor.fetchall() conn.close() to_remove = [] for user in accepted_users: conn, cursor = connect() query = "select following from user where chatId = '{0}'".format( user[0]) cursor.execute(query) following = cursor.fetchall()[0][0] conn.close() following = following.strip() if (following == ""): continue following = following.split(' ') for usr in following: message = "" if (usr in data): message = "Status update of " + usr + " for the day " + date + '\n\n' message = message + data[usr] print(message) else: if (usr in all_mails): message = usr + " Did not send a status update for the day " + date + '\n' else: to_remove.append(usr) message = usr + " No longer exists in the mails database, so the user has been removed from your following list" send_message(user[0], message, True) if (len(to_remove) > 0): print(to_remove) for mail in to_remove: following = list(filter((mail).__ne__, following)) conn, cursor = connect() query = "update user set following = '" + ' '.join( following) + "' where chatId = " + user[0] cursor.execute(query) conn.commit() conn.close()
def main(): connect(sys.argv[1]) data= retrievedata(sys.argv[2]) print data pl.plot(data, hold= True) smoothed = np.convolve(data, np.ones(10)/10) print sumstatextract(smoothed) #print smoothed pl.plot(smoothed) prepare_figure() pl.show()
def create_app(config): app = Flask(__name__, template_folder='templates', static_folder=None) app.debug = config.get('debug') or False app.secret_key = config.get('secret') or 'DANGEROUS SECURE' db.connect() config['api_keys'] = (config.get('api_keys') or []) + [ str(uuid.uuid5(uuid.NAMESPACE_DNS, app.secret_key)) ] def teardown(exception=None): db.session.remove() return exception def exception_handler(exception): db.session.rollback() return exception blueprint = Blueprint('api', 'api', url_prefix='/api') api = Api(blueprint, endpoint='api', authorizations={ 'apikey': { 'type': 'apiKey', 'in': 'header', 'name': 'X-API-Key' }, 'cookieAuth': { 'type': 'apiKey', 'in': 'cookie', 'name': 'session', } }) for a in apis.get_apis(): api.add_namespace(a) app.teardown_request(teardown) app.register_error_handler(Exception, exception_handler) app.register_blueprint(blueprint) app.register_blueprint(views.index.app) app.url_map.strict_slashes = False if config['debug']: logging.info(app.url_map) cors = CORS(app, resources={r"/api/*": { "origins": "*" }}, supports_credentials=True) return app
def start(): view.print_welcome() database.connect() app_running = True while app_running: view.print_options() chosen_option = input("Choose... ") handled_chosen_option = handle_chosen_option(chosen_option) os.system('clear') if handled_chosen_option: view.print_results(handled_chosen_option) elif handled_chosen_option == []: view.zero_attendance() else: view.print_wrong_input_alert()
def main(): filename = sys.argv[-1] # Get the last agument passed to the file name if filename == "main.py": print("Error: No database passed to file") print("Exiting program...") sys.exit() path = "./" + filename db.connect(path) isQuit = False while not isQuit: start() mainMenu() clear_screen() db.cur_user = None # User has logged out, set user to none
def start_image_processor(env, services, loop=True, wait=False ): db = database.connect(env) # generate array of ( pool, requests ) tupels, with a thread pool and # a dictionary with for this pool currently open requests pool_requests = [] for service_processor_factory in services: pool_requests.append( ( thread_pool.ThreadPool( POOL_SIZE, process_class_factory= service_processor_factory ), {} ) ) while True: try: for row in db.unprocessed_docs_view(): for pool, requests in pool_requests: if row.id in requests and not requests[row.id].has_timed_out(): continue request_id = pool.schedule_work(db, row.id) requests[row.id] = Request(request_id) except Exception, e: logger.exception("Exception in while processing view: '%s'", e) if not loop: break else: time.sleep(0.5)
def _fetchall(sql): db = connect() cursor = db.cursor() cursor.execute(sql) data = np.array(cursor.fetchall()) db.close() return data
def main(): conn = connect(sys.argv[1]) n = int(sys.argv[2]) cur = conn.cursor() cur.execute( '''CREATE TABLE IF NOT EXISTS sir_runs ( id SERIAL PRIMARY KEY, gamma REAL, beta REAL )''') cur.execute( '''CREATE TABLE IF NOT EXISTS sir_results ( id INTEGER REFERENCES sir_runs, s INTEGER, i INTEGER, r INTEGER, t SMALLINT );''') conn.commit() sr = sweep_range(0.99, 0.01, n) for g, b, sw in sweep(1000, 5, 0, sr, sr): print g, b, len(sw) cur.execute( '''INSERT INTO sir_runs (gamma, beta) VALUES (%s, %s) RETURNING id;''', (g, b)) id, = cur.fetchone() for t in xrange(len(sw)): s, i, r = sw[t] cur.execute( 'INSERT INTO sir_results VALUES (%s, %s, %s, %s, %s);', (id, s, i, r, t)) conn.commit()
def delete_pressed(self): id = self.id_entry.get() if id == "" or id == "Select ID of the transaction from the table.": messagebox.showinfo(title="Unsuccessful", message="Please select id") else: connection = database.connect() is_done = database.delete_transaction(connection, self.table, id) if is_done: messagebox.showinfo(title="Successful", message="Transaction deleted.☑") for i in self.Transaction_table.get_children(): self.Transaction_table.delete(i) data = database.get_delete_table(connection, self.table) i = 0 for row in data: self.Transaction_table.insert('', i, values=(row[0], row[1], row[2], row[3], row[4], row[5])) i = i + 1 self.id_entry.delete(0, END) else: messagebox.showinfo(title="Unsuccessful", message="Please select a valid id") self.id_entry.delete(0, END)
def modify_quantity(self, product, new_quantity): db = database.connect() cursor = database.get_cursor(db) if isinstance(new_quantity, int) and new_quantity >= 0: product_id = product.get_id() cursor.execute("select quantity from warehouse_to_product \ where product_id = :input_pid and warehouse_id = :input_wid" , \ input_pid = product_id, input_wid = self.get_id()) current_quantity = cursor.fetchone() if current_quantity: # Ensuring product is in warehouse stock current_quantity = int(current_quantity[0]) if current_quantity == new_quantity: # Do nothing if quantity doesn't change pass elif new_quantity == 0: # Remove line in DB is new quantity is zero cursor.execute("delete from warehouse_to_product \ where product_id = :input_pid and warehouse_id = :input_wid" , \ input_pid = product_id, input_wid = self.get_id()) database.commit(db) else: # Otherwise just update the quantity cursor.execute("update warehouse_to_product set quantity = :input_quantity \ where product_id = :input_pid and warehouse_id = :input_wid" , \ input_quantity = new_quantity, input_pid = product_id, \ input_wid = self.get_id()) database.commit(db) else: raise ValueError("new quantity must be positive integer value") database.disconnect(db)
def testdb(): ''' base de datos ''' import database as db database = 'sqlite:///test.sqlite' db.create(database) s = db.connect(database) user = db.User('dani', 'pass') password = db.Password('mi pass', 'asfsdaf') conffile = db.Conffile('mi file', 'file', '') cookie = db.Cookie() user.passwords = [password] user.conffiles = [conffile] user.cookie = cookie s.save(user) s.commit() u = s.query(db.User).first() assert u.name == 'dani' assert u.password != 'pass' assert u.passwords[0].name == 'mi pass' assert u.conffiles[0].name == 'mi file'
def deleteFriend(): if not checkReady(): return fail('The API is still booting up... Please wait.') log('Removing friend...') if not checkAccessToken(): sublog('Bad access token.') return fail('Invalid access token.') if not 'friend' in request.json.keys(): sublog('No friend specified.') return fail('No friend specified.') thisUser = accessTokenToUser(request.json['accessToken']) sublog('Name: ' + thisUser + '\n\tFriend: ' + request.json['friend']) con = database.connect() c = con.cursor() c.execute("DELETE FROM friends WHERE username=:username and friend=:friend", {'username': thisUser, 'friend': request.json['friend']}) database.close(con) sublog('Friend removed.') return success('Friend removed!')
def addFriend(): """Adds a friend to someone's friend list.""" if not checkReady(): return fail('The API is still booting up... Please wait.') log('Adding friend...') if not checkAccessToken(): sublog('Bad access token.') return fail('Invalid access token.') if not 'friend' in request.json.keys(): sublog('No friend specified.') return fail('No friend specified.') thisUser = accessTokenToUser(request.json['accessToken']) sublog('Name: ' + thisUser + '\n\tFriend: ' + request.json['friend']) if request.json['friend'] == thisUser: sublog('User tried to add themself as friend...') return fail('You can\'t add yourself as a friend...') con = database.connect() c = con.cursor() c.execute("INSERT OR IGNORE INTO friends (username, friend) VALUES (:username, :friend)", {'username': thisUser, 'friend': request.json['friend']}) database.close(con) sublog('Friend added.') return success('Friend added!')
def getFriends(): """Get the friends list of a client.""" if not checkReady(): return fail('The API is still booting up... Please wait.') log('Checking friends list...') if not checkAccessToken(): sublog('Bad access token.') return fail('Invalid access token.') thisUser = accessTokenToUser(request.json['accessToken']) sublog('Name: ' + thisUser) con = database.connect() c = con.cursor() c.execute("SELECT friend FROM friends WHERE username=:username", {'username': thisUser}) res = jsonRows(c) database.close(con) sublog('Ok.') return res
def imageSeen(): """Set an image's hop count to -1 so it won't appear in the list of images the client gets when they query.""" if not checkReady(): return fail('The API is still booting up... Please wait.') log('Marking image as seen...') if not checkAccessToken(): sublog('Bad access token.') return fail('Invalid access token.') if not 'uuid' in request.json.keys(): sublog('No UUID specified.') return fail('No UUID specified.') # Make sure a client can only mark their own images as seen, and only images that have a hopCount of 0. thisUser = accessTokenToUser(request.json['accessToken']) sublog('Name: ' + thisUser) con = database.connect() c = con.cursor() c.execute("UPDATE imageHistory SET viewed=1 WHERE imageUUID=:imageUUID AND username=:username", {'imageUUID': request.json['uuid'], 'username': thisUser}) database.close(con) sublog('Acknowledgement complete.') return success('Successfully acknowledged image.')
def imageCreate(): """Create an initial image.""" if not checkReady(): return fail('The API is still booting up... Please wait.') log('Creating the first image...') if not checkAccessToken(): sublog('No access token.') return fail('Invalid access token.') if not 'editTime' in request.json.keys(): sublog('No editTime specified.') return fail('No editTime specified.') if not 'hopsLeft' in request.json.keys(): sublog('No hopsLeft specified.') return fail('No hopsLeft specified.') if not 'nextUser' in request.json.keys(): sublog('No nextUser specified.') return fail('No nextUser specified.') if not 'image' in request.json.keys(): sublog('No image specified.') return fail('No image specified.') sublog('Edit time: ' + str(request.json['editTime']) + '\n\tHops: ' + str( request.json['hopsLeft']) + '\n\tNext user: '******'nextUser'] + '\n\tImage: (yes)') # Make sure the next user is valid... con = database.connect() c = con.cursor() c.execute("SELECT COUNT(*) FROM users WHERE username=:nextUser", {'nextUser': request.json['nextUser']}) r = c.fetchone() if r[0] == 0: database.close(con) sublog('Next user was not valid.') return fail('Invalid nextUser.') # Add the image to the pending queue. thisUser = accessTokenToUser(request.json['accessToken']) thisImageUUID = str(uuid.uuid1()) sublog('Name: ' + thisUser) c.execute( "INSERT INTO images (imageUUID, originalOwner, hopsLeft, editTime, image, nextUser, previousUser) VALUES (:imageUUID, :originalOwner, :hopsLeft, :editTime, :image, :nextUser, :previousUser)", {'imageUUID': thisImageUUID, 'originalOwner': thisUser, 'hopsLeft': request.json['hopsLeft'], 'editTime': request.json['editTime'], 'image': request.json['image'], 'nextUser': request.json['nextUser'], 'previousUser': thisUser}) # Add the initial creator into the log of people who should be notified when this image is done. c.execute("INSERT INTO imageHistory (imageUUID, username) VALUES (:imageUUID, :username)", {'imageUUID': thisImageUUID, 'username': thisUser}) # TODO: Send push notification to the next user. database.close(con) sublog('Image created.') return success('Image created and next user will be alerted.')
def read_drinksdb(): connect() from database import connection global drinks drinks = [] cursor_drinks = connection.cursor() cursor_drinks.execute("SELECT name, category, volume, price FROM drink") rowsd = cursor_drinks.fetchall() for row in rowsd: drink = Drinks(row[0], row[1], row[2], row[3]) drinks.append(drink) cursor_drinks.close() connection.close()
def gen(): last_id = 0 conn = db.connect() cur = conn.cursor() try: while True: data = [] cur.execute('SELECT id, url, created, json FROM photos WHERE id > ? AND json IS NOT NULL ORDER BY id;', (last_id,)) while True: row = cur.fetchone() if row is None: break id, url, created, json_text = row data.append({'id':id, 'url':"/photos/%s" % (id,), 'created':created, 'json':json.loads(json_text)}) last_id = max(id, last_id) if data: event = json.dumps(data) print "Sending event %s" % (event,) yield "data: %s\n\n" % (event,) time.sleep(1) except GeneratorExit: pass conn.close()
def remove_mail(chatId, mails): mails = list(set(mails)) conn, cursor = connect() not_present = [] removed_mail = [] for mail in mails: try: if (is_valid_mail(mail)): query = "delete from mail where mail_id = '{0}';".format(mail) cursor.execute(query) conn.commit() removed_mail.append(mail) else: not_present.append(mail) except (MySQLdb.Error, MySQLdb.Warning) as e: app.logger.info(e) send_error_message(chatId) conn.close() return message = "No changes done\n" if (len(removed_mail) > 0): message = "Deleted the following from the database\n" for mail in removed_mail: message = message + " ->" + mail + '\n' if (len(not_present)): message = message + "The following do not exist in the database\n" for mail in not_present: message = message + " ->" + mail + '\n' send_message(chatId, message) return
def update_task(task_data): """Update a task""" id = int(task_data["id"]) user_id = int(task_data["user_id"]) description = task_data["description"] due_date = int(task_data["due_date"]) priority = int(task_data["priority"]) if check_task_id(id): # If task id exist # Open connection and execute SQL to update a task try: db, cursor = connect() cursor.execute("""UPDATE tasks SET user_id=%s, description=%s, due_date=%s, priority=%s WHERE id=%s """, (user_id, description, due_date, priority, id) ) db.commit() # Get error messages except catch_error(), e: print "Error %d: %s" % (e.args[0],e.args[1]) # Close connection finally:
def remove_product(self, product): db = database.connect() cursor = database.get_cursor(db) product_id = product.get_id() cursor.execute("select quantity from warehouse_to_product \ where product_id = :input_pid and warehouse_id = :input_wid" , \ input_pid = product_id, input_wid = self.get_id()) current_quantity = cursor.fetchone() if current_quantity: # The item is already in this table in the DB, just decriment quantity decrimented_quantity = int(current_quantity[0]) - 1 if decrimented_quantity > 0: # Removing one will not remove all instances of that product cursor.execute("update warehouse_to_product set quantity = :input_quantity \ where product_id = :input_pid and warehouse_id = :input_wid" , \ input_quantity = decrimented_quantity, input_pid = product_id, \ input_wid = self.get_id()) database.commit(db) else: # Remove the line from the DB if product has quantity of zero cursor.execute("delete from warehouse_to_product \ where product_id = :input_pid and warehouse_id = :input_wid" , \ input_pid = product_id, input_wid = self.get_id()) database.commit(db) else: # The item is not yet in the warehouse's stock, so do nothing pass database.disconnect(db)
def index(): email = None password = None if request.method == 'POST': email = request.form['email'] password = request.form['password'] first_name = 'Aaron' last_name = 'Blaser' perm = 1 position_id = 1 error = 0 if not (email and not (email == '' or email == ' ')): error += 1 if not (password and not (password == '' or password == ' ')): error += 1 if error == 0: sql = "INSERT INTO users (email, first_name, last_name, password, permission_id, position_id) VALUES (%s, %s, %s, %s, %s, %s)" data = [email, first_name, last_name, password, perm, position_id] db, cursor = connect() cursor.execute(sql, data) db.commit() db.close() else: print("There Was an Error.") return render_template('index.html', email=email, password=password)
def new_warehouse(capacity, street, city, state_string, zip_code, apartment_no=None): # Adding new warehouse to database, and returning reference to that warehouse db = database.connect() cursor = database.get_cursor(db) warehouse_address = address.Address.new_address(street, city, state_string, zip_code,\ "warehouse", apt_no = apartment_no) address_id = warehouse_address.get_id() if isinstance(capacity, (int, float)): returned_id = cursor.var(database.cx_Oracle.NUMBER) capacity = int(capacity) cursor.execute("insert into warehouses \ (capacity, address_id) values (:input_capacity, :input_address) \ returning id into :new_warehouse_id" , \ input_capacity = capacity, input_address = address_id, \ new_warehouse_id = returned_id) database.commit(db) returned_id = int(returned_id.getvalue()) database.disconnect(db) return Warehouse(returned_id)
def user_by_cookie(cookie, session=None): ''' Return the user with that cookie. If cookie is expired or not found raises BadCookieError session is a database.connect() object ''' close_it = False if not session: session = db.connect(DATABASE) try: user = session.query(db.User).\ filter(db.User.id == db.Cookie.user_id).\ filter(db.Cookie.id == cookie).one() expiration = user.cookie.expiration except db.InvalidRequestError: raise BadCookieError("cookie can't be found") # Comprobar que la cookie no está caducada if expiration < datetime.datetime.now(): raise BadCookieError("cookie has expired") else: return user
def menu(): connection = database.connect() database.create_tables(connection) while (user_input := input(MENU_PROMPT)) != "5": if user_input == "1": name = input("Enter your bean name: ") method = input("Enter how you've prepared it") rating = int(input("Enter your rating score (0-100): ")) database.add_bean(connection, name, method, rating) elif user_input == "2": beans = database.get_all_beans(connection) for bean in beans: print(f"{bean[1]}{bean[2]}{bean[3]}") elif user_input == "3": name = input("Enter bean name to find: ") beans = database.get_beans_by_name(connection, name) for bean in beans: print(f"{bean[1]}{bean[2]}{bean[3]}") elif user_input == "4": name = input("Enter bean name to find: ") best_method = database.get_best_preparation_for_bean(connection, name) print(f"The best preparation method for {name} is {best_method[2]}") elif user_input == "5": pass else: pass
def test(): login = request.cookies.get('test_login') connection = database.connect() if not login: # если сюда попал неавторизированный пользователь, то переход на страницу с входом return redirect('/enter') if request.method == 'POST': if 'exit' in request.form: # если нажали на кнопку выхода res = redirect('/enter') res.set_cookie('test_login', '', max_age=0) # удаление куки о пользователе return res else: # если получили ответ от формы (от теста) points = 0 answers = [] questions = database.get_all_questions( connection) # получаем все вопросы с ответами for question in questions: id, correct_answer = str(question[0]), str(question[6]) answer = request.form.get(id) # берем ответ из формы answers.append(answer) if answer == correct_answer: # сравниваем ответ с верным points += 1 # добавляем результаты в БД database.add_result(connection, login, ' '.join(answers), points) return redirect('/results') else: test = database.get_all_questions(connection) return render_template('test.html', login=login, test=test)
def findByCalled(cls, called): with connect() as conn: with conn.cursor() as cursor: cursor.execute( 'SELECT * FROM organizations WHERE called ILIKE %s', ("%" + called + "%", )) rows = cursor.fetchall() return [ cls(row[1], row[2], row[3], row[4], row[5], row[6], row[7]) for row in rows ] # class Company(Organization): # def __init__(self, called, longName, legalName, uri, emailSuffix, dataRegistered): # super().__init__(called, longName, legalName, uri, emailSuffix, dataRegistered) # # # class PortfolioCompany(Company): # def __init__(self, called="", longName="", legalName="", uri="", emailSuffix="", dataRegistered=""): # super().__init__(called, longName, legalName, uri, emailSuffix, dataRegistered) # # # makeSchool = PortfolioCompany(called="MakeSchool", legalName="Make Games With Us", uri="http://makeschool.com") # # print(makeSchool.legalName)
def doc(id): conn = db.connect() post = db.fetch(conn, id) return render_template('doc.html', ID=post.id, TITLE=post.title, TEXT=post.body)
def getByUUID(cls, uuid): with connect() as conn: with conn.cursor() as cursor: cursor.execute('SELECT * FROM persons WHERE uuid=%s', (uuid, )) row = cursor.fetchone() return cls(row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9])
def install_deps(self, distro, force_yes): import database db = database.connect(self.ver3) deps = db.dependencies(self.pkg_name, False) if deps != "NULL": if distro == "arch": if force_yes == True: manager = "sudo pacman --needed --noconfirm -S " else: manager = "sudo pacman --needed -S " elif distro == "debian": if force_yes == True: manager = "sudo apt-get -f install " else: manager = "sudo apt-get install " elif distro == "fedora": if force_yes == True: manager = "sudo yum -f install " else: manager = "sudo yum install " check_call(manager + deps, shell = True) else: pass
def pkg(self, package, distro): print(" [+] Deleting %s source files..." % package) if package in listdir("/usr/bin"): check_call("sudo rm -rf /usr/bin/%s" % package, shell=True) check_call("sudo rm -rf /usr/share/%s" % package, shell=True) elif package in listdir("/usr/local/bin"): check_call("sudo rm -rf /usr/local/bin/%s" % package, shell=True) check_call("sudo rm -rf /usr/local/share/%s" % package, shell=True) else: print(" [!] %s not installed" % package) exit() if self.conf == True: check_call("sudo rm -rf /etc/%s" % package, shell=True) if self.deps == True: import database deps = database.connect(self.ver3).dependencies(package) if distro == "arch": command = "sudo pacman -Rsn %s" % deps elif distro == "debian": command = " sudo apt-get remove %s" % deps elif distro == "fedora": command = "sudo yum remove %s" % deps check_call(command, shell=True)
def login(): username = "" errors = {} global user if request.method == "POST": username = request.form.get("username").strip() if not username: errors["username"] = "******" password = request.form.get("password").strip() if not password: errors["password"] = "******" if len(errors) == 0: with database.connect() as conn: tmp = database.login(conn, username, password) if tmp == -1: errors["username"] = username + " does not exist" elif tmp == -2: errors["password"] = "******" else: user = User(tmp[0][0], tmp[0][1], tmp[0][2], tmp[0][3]) print("Successfully Logged In!") return redirect("/") return render_template("login.html", username=username, errors=errors, tab="login", user=user)
def init(dirs): updateDirs(dirs) # init database is_db_exists = database.connect() if not is_db_exists: Track().create_table() Folder().create_table()
def add_mail(chatId, mails): mails = list(set(mails)) conn, cursor = connect() already_exist = [] added_mail = [] for mail in mails: try: if (is_valid_mail(mail)): already_exist.append(mail) else: query = "insert into mails (mail_id) values ('{0}');".format( mail) cursor.execute(query) conn.commit() added_mail.append(mail) except (MySQLdb.Error, MySQLdb.Warning) as e: app.logger.info(e) send_error_message(chatId) conn.close() return message = "No changes done\n" if (len(added_mail) > 0): message = "Inserted the following into the database\n" for mail in added_mail: message = message + " ->" + mail + '\n' if (len(already_exist)): message = message + "The following already exist in the database\n" for mail in already_exist: message = message + " ->" + mail send_message(chatId, message) return
def get_tabledata2(): """ Gets data from the database and splits into features and labels :return: X, y """ rows = database.connect() return rows
def pkg(self, package, distro): print(" [+] Deleting %s source files..." % package) if package in listdir("/usr/bin"): check_call("sudo rm -rf /usr/bin/%s" % package, shell = True) check_call("sudo rm -rf /usr/share/%s" % package, shell = True) elif package in listdir("/usr/local/bin"): check_call("sudo rm -rf /usr/local/bin/%s" % package, shell = True) check_call("sudo rm -rf /usr/local/share/%s" % package, shell = True) else: print(" [!] %s not installed" % package) exit() if self.conf == True: check_call("sudo rm -rf /etc/%s" % package, shell = True) if self.deps == True: import database deps = database.connect(self.ver3).dependencies(package) if distro == "arch": command = "sudo pacman -Rsn %s" % deps elif distro == "debian": command = " sudo apt-get remove %s" % deps elif distro == "fedora": command = "sudo yum remove %s" % deps check_call(command, shell = True)
def update_task_status(id, status): """Update task status""" id = int(id) if check_task_id(id): # If task id exist # Open connection and execute SQL to update task status try: db, cursor = connect() cursor.execute("""UPDATE tasks SET status=%s WHERE id=%s """, (status, id) ) db.commit() result = True # Get error messages except catch_error(), e: result = False print "Error %d: %s" % (e.args[0],e.args[1]) # Close connection finally:
def menu(): connection = database.connect() database.create_tables(connection) while (user_input := input(MENU_PROMPT)) != "0": if user_input == "1": card_number = generate_card_number() pin = generate_pin() database.add_card(connection, card_number, pin) print("Your card has been created") print(f"Your card number:\n{card_number}") print(f"Your card PIN:\n{pin}") elif user_input == "2": card_number = input("Enter your card number:\n") entered_pin = input("Enter your PIN:\n") if database.get_pin_by_number(connection, card_number) == entered_pin: print("You have successfully logged in!") while True: user_input = input(LOGGED_IN_MENU_PROMPT) if user_input == "1": print(f"Balance: {database.get_balance_by_number(connection, card_number)}") elif user_input == "2": income = input("Enter income:\n") database.add_income(connection, income, card_number) print("Income was added!") elif user_input == "3": print("Transfer") recipient = input("Enter card number: ") if recipient != card_number: if check_luhn(recipient): x = database.get_card_by_number(connection, recipient) if x is not None: payment = int(input("Enter how much money you want to transfer:\n")) if payment <= database.get_balance_by_number(connection, card_number): database.add_forfeit(connection, payment, card_number) database.add_income(connection, payment, recipient) print("Success!") else: print("Not enough money!") else: print("Such a card does not exist.") else: print("Probably you made a mistake in the card number. Please try again!") else: print("You can't transfer money to the same account!") elif user_input == "4": database.delete_by_number(connection, card_number) print("The account has been closed!") break elif user_input == "5": print("You have successfully logged out!") break elif user_input == "0": print("Bye!") exit() else: print("Wrong card number or PIN!")
def index(): #uid = session.get ("my_uid") with database.connect() as conn: database.initTable(conn) global user #user = database.getUser (conn, "admin") return render_template("index.html", tab="index", user=user)
def insertIntoDatabase(expId, malBehaviorNumber, length, resultingData): connection = db.connect() # exclude the header and only insert the pure data in the database resultingData = resultingData[1:] db.insertLocalizationBrute(connection, expId, length, malBehaviorNumber, resultingData) db.close(connection)
def main(): conn = connect(sys.argv[1]) create_table(conn) for row in read_csv(country_list()): insert_row(conn, row) print row conn.commit()
def extract_media_url(data): try: original = True if 'retweeted_status' in data: if data['retweeted_status']['created_at'] != data['created_at']: original = False ents = data.get('entities', {}).get('media', []) if ents: for ent in ents: try: if original: created_at = parse_date(data['created_at']) url = ent['media_url'] conn = db.connect() cur = conn.cursor() cur.execute('SELECT * from photos WHERE url=?;', (url,)) if cur.fetchone() is None: cur.execute('INSERT INTO photos(url, created) VALUES (?, ?);', (url, created_at.isoformat())) logger.info("Added tweet: %s", url) else: logger.info("Not adding: tweet is already there") conn.commit() conn.close() else: logger.info("Not adding: tweet is not original") except Exception: logger.exception("Unexpected exception") else: logger.info("Not adding: tweet has no media") except Exception: logger.exception("Unexpected exception")
def Main(fileMap, fileoutput, limit): outputDir = 'parsed_' + str(datetime.datetime.now()) print("Extraindo dados do Perfil de Eleitores...") parsePerfilEleitorado(fileMap, outputDir, limit) print("Extraindo dados do Perfil de Candidatos...") parseCandidaturas(fileMap, outputDir, limit) print("Extraindo dados do resultado das Seções Eleitorais...") parseSecoesEleitorais(fileMap, outputDir, limit) print("Criando Banco de Dados...") db = database.connect(fileoutput) insertMasterData(db, outputDir) insertMunicipios(db, outputDir) insertZonas(db, outputDir) insertDemografia(db, outputDir) insertCandidatos(db, outputDir) insertCandidaturas(db, outputDir) insertEleicoes(db, outputDir) utils.clearDir(outputDir) print("Done!")
def run(self): database.connect() dbconnection = database.get_dbconnection() cursor = dbconnection.cursor() while True: if osp.exists('../stop_daemons'): self.log.printf(NORMAL,"Stop deamons file found.\n") sys.exit() try: dbconnection.commit() app = database.Apps.find1(name=self.appname) num_unsent = database.Results.count(app=app, server_state=RESULT_SERVER_STATE_UNSENT) if num_unsent<self.args['cushion'][0]: num_create = self.args['cushion'][0]-num_unsent self.log.printf(NORMAL,"%i unsent results. Creating %i more.\n",num_unsent,num_create) self.make_jobs(num=num_create) # wait for transitioner to create jobs now = int(time()) while True: self.log.printf(DEBUG,"Waiting for transitioner...\n") dbconnection.commit() cursor.execute("select min(transition_time) as t from workunit") if cursor.fetchone()['t']>now: break sleep(1) self.log.printf(DEBUG,"Created.\n") continue else: self.log.printf(DEBUG,"%i unsent results.\n",num_unsent) except CheckOutputError: pass except Exception as e: self.log.printf(CRITICAL,"Error: %s\n",str(e)) traceback.print_exception(type(e), e, sys.exc_info()[2], None, sys.stderr) sleep(int(self.args['sleep_interval'][0]))
def install(): if "btnSubmit" in request.all: installservice.setupConfigFile( dbServer = request.all["databaseServer"], dbName = request.all["databaseName"], dbUser = request.all["databaseUserName"], dbPass = request.all["databasePassword"], blogTitle = request.all["blogTitle"], postsPerPage = request.all["postsPerPage"], hashKey1 = request.all["hashKey1"], hashKey2 = request.all["hashKey2"], encryptionKey = request.all["encryptionKey"], encryptionIV = request.all["encryptionIV"] ) installservice.setupDatabase( dbServer = request.all["databaseServer"], dbPort = 3306, dbName = request.all["databaseName"], dbUser = request.all["databaseUserName"], dbPass = request.all["databasePassword"], email = request.all["adminEmail"], password = request.all["adminPassword"], firstName = request.all["adminFirstName"], lastName = request.all["adminLastName"], timezone = request.all["timezone"], hashKey1 = request.all["hashKey1"], hashKey2 = request.all["hashKey2"], ) database.disconnect() imp.reload(config) database.connect( engine = "mysql", host = config.ENVIRONMENT["DB_HOST"], port = config.ENVIRONMENT["DB_PORT"], database = config.ENVIRONMENT["DB_NAME"], user = config.ENVIRONMENT["DB_USER"], password = config.ENVIRONMENT["DB_PASSWORD"] ) redirect("/installcomplete") return { "timezones": dthelper.getTimezoneArray() }
def main(): global account_manager print "Starting server on %s." % HOST account_manager = AccountManager() database.connect() money_thread = threading.Thread(target = money_receiver) phone_thread = threading.Thread(target = phone_receiver) rfid_thread = threading.Thread(target = rfid_receiver) dispenser_thread = threading.Thread(target = dispenser_controller) money_thread.start() phone_thread.start() rfid_thread.start() if settings.DISPENSER == NORMAL: dispenser_thread.start()