from database import DataBase from sys import argv from url_opener import Opener print('What do you want to do?') print('To create database write: main.py create_database') print('Create table write: main.py create_table') print('Insert url write: main.py insert -name- -url-') print('Display all url\'s write: main.py display') print('Open websites write: main.py open') print('Open delete page from database write: main.py delete -name-') if len(argv) == 2 and argv[1] == 'create_database': db = DataBase() if len(argv) == 2 and argv[1] == 'create_table': db = DataBase() db.create_table() if len(argv) == 4 and argv[1] == 'insert' and argv[2] and argv[3]: db = DataBase() db.insert(name=argv[2],url=argv[3]) if len(argv) == 2 and argv[1] == 'display': db = DataBase() db.display() if len(argv) == 2 and argv[1] == 'open': urls = DataBase() opening = Opener(urls.open()) opening.opener()
def __init__(self, output_folder): self.db = DataBase() self.actions_list = ["Up", "Down", "Left", "Right"] self.output_folder = output_folder
#!/usr/bin/env python # -*- coding: utf-8 -*- # This program is dedicated to the public domain under the CC0 license. import logging import os import sys from telegram import * from telegram.ext import Updater, CommandHandler, CallbackQueryHandler from database import DataBase DB = DataBase('data.sql') TOKEN = os.environ.get('TOKEN') if TOKEN == None: print('Define TOKEN env var!') sys.exit(1) # Enable logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) def dota(update, context): if len(context.args) == 0: keyboard = [[ InlineKeyboardButton("Patches", callback_data="patches"),
import telebot from telebot import types from monica import Chatbot from database import DataBase import time uradb = DataBase() while True: tkn = "" # Requires the monica's chatbot token bot = telebot.TeleBot(tkn) monica = Chatbot() def req_monica(message): return True @bot.message_handler(commands=["start"]) def start(message): global user bot.send_chat_action(message.chat.id, "typing") msg = "Olá! Eu sou a Mônica, a assistente virtual de Uberaba. Como posso te ajudar hoje?" bot.send_message(message.chat.id, msg) monica.user = uradb.get_telegram_user(message.chat.id) print(f"Usuário conectado: {monica.user[2]}") @bot.message_handler(func=req_monica) def monica_response(message): if not monica.user: monica.user = uradb.get_telegram_user(message.chat.id)
def invalidForm(): pop = Popup(title='Invalid Form', content=Label( text='Please fill in all inputs with valid information.'), size_hint=(None, None), size=(400, 400)) pop.open() kv = Builder.load_file("my.kv") # Chama e constroi com o arquivo .kv sm = WindowManager() db = DataBase( "users.txt" ) # Passa o arquivo de texto para o tratamento pela "geatabase.py" screens = [ LoginWindow(name="login"), CreateAccountWindow(name="create"), MainWindow(name="main") ] for screen in screens: sm.add_widget(screen) sm.current = "login" # Aqui indica qual é a tela inicial class MyMainApp(App): def build(self):
def invalidForm(): pop = Popup(title='Invalid Form', content=Label( text='Please fill in all inputs with valid information.'), size_hint=(None, None), size=(400, 400)) pop.open() kv = Builder.load_file("login.kv") sm = WindowManager() db = DataBase("users.txt") screens = [ LoginWindow(name="login"), CreateAccountWindow(name="create"), MainWindow(name="main") ] for screen in screens: sm.add_widget(screen) sm.current = "login" class MyMainApp(App): def build(self): return sm
from database import DataBase a = DataBase() print(a.reg_user('ganievi','1234')) print(a.log_user('ganievi','1234'))
self.export_to_png(f"{dirname(__file__)}\draw\IMG_" + timestr + ".png") class KidInputScreen(Screen): def __init__(self, **kwargs): # super(KidInputScreen, self).__init__(**kwargs) self.kp = SelectionTool() #네모 그리는 클래스 가져옴 self.add_widget(self.kp) class KidVideoScreen(Screen): pass class Manager(ScreenManager): pass db = DataBase(f"{dirname(__file__)}/users.csv") class CoronaApp(MDApp): username = StringProperty(None) # 이름 입력값 password = StringProperty(None) # P/W 입력값 def build(self): return Manager() if __name__ == '__main__': CoronaApp().run()
def update_database(): global settings db = DataBase() db.create() img_paths = [] for (dirpath, dirnames, filenames) in os.walk(settings.path): for f in filenames: if is_photo(f): img_paths.append(os.path.join(dirpath, f)) n = len(img_paths) i = 1.0 img_ids_to_uplod = [] img_paths_to_upload = {} for img_path in img_paths: Logger.info("Update database progress {}".format(100.0 * i / n)) i = i + 1.0 img_id = db.get_photo_id(img_path) if img_id != -1: # Photo is already in the database Logger.debug("Photo is already in the database: " + img_path) continue img_id = db.insert_photo(img_path) Logger.debug("Photo inserted in db: {}, {}".format(img_path, img_id)) img_ids_to_uplod.append(img_id) img_paths_to_upload[img_id] = img_path if len(img_ids_to_uplod) == 0: db.close() return for i in range(int(len(img_ids_to_uplod) / settings.facedet_batch) + 1): start = i * settings.facedet_batch end = min(len(img_ids_to_uplod), (i + 1) * settings.facedet_batch) img_paths = [ img_paths_to_upload[id] for id in img_ids_to_uplod[start:end] ] conn = Connection(settings.facedet_host, settings.facedet_port) conn.send_message("objdet") conn.upload_images(img_paths, img_ids_to_uplod[start:end]) ret = conn.get_response() Logger.debug("Got " + ret) records = ret.split(':') for record in records: if record == "END": break tokens = record.split(';') if len(tokens) != 6: Logger.error( "Error in update_database: invalid number of tokens " + len(record) + " in record [" + record + "]") else: db.insert_box(tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[0]) conn.close() db.close()
def updateDatabase(): db_user = DataBase("users.txt") db_partner = DataBase("restaurants.txt")
from database import DataBase from config import Config config = Config() db = DataBase(config.get_mongodb_link(), config.get_db_name(), config.get_collection()) account = db.log_in()
size_hint=(None, None), size=(400, 400)) pop.open() def updateDatabase(): db_user = DataBase("users.txt") db_partner = DataBase("restaurants.txt") kv = Builder.load_file("my.kv") sm = WindowManager() db_user = DataBase("users.txt") db_partner = DataBase("restaurants.txt") screens = [ LoginWindow(name="login"), CreateAccountWindow(name="create"), MainWindow(name="main"), HomeWindow(name="home"), PartnerLoginWindow(name="partnerlogin"), PartnerCreateAccountWindow(name="partnercreate"), PartnerMainWindow(name="partnermain"), AddFood(name="addfood"), UpdateFood(name="updatefood"), ViewWindow(name="view"), OrderWindow(name="order") ]
errorPopup.open() # for selecting "ALL" in city window when user specifies "one-day" forecast def errorAll(): errorPopup = Popup(title = "ERROR", content = Label(text = "Error! One cannot select *All* when \nsending a one-day precipitation forecast."), \ size_hint = (None, None), size = (400, 400)) errorPopup.open() ## Class instances kv = Builder.load_file("main.kv") # load main.kv file sm = WindowManager() # load WindowManager upon running sv = SaveText() # access to functions for storing text gb = Globals() # access to "global variables and functions" db = DataBase("data.txt") # load database mc = MakeCalls() # allow access to Twilio # create screens list that assigns name (ID) to each class screens = [HomeWindow(name = "home"), CityWindow(name = "city"), OneDayParameterWindow(name = "one_day_main"), MediumRangeWindow(name = "medium_range"), \ PreviewWindow(name = "preview"), SentWindow(name = "sent")] for screen in screens: sm.add_widget(screen) sm.current = "home" # by default, current screen goes to HomeWindow # builds the kivy application class ForecastSendApp(App): def build(self): return sm
def __init__(self, id_patient=None, id_medecin=None): Toplevel.__init__(self) x, y = int((self.winfo_screenwidth() / 2) - 279.5), int((self.winfo_screenheight() / 2) - 152.5) self.geometry("559x305+{0}+{1}".format(x, y)) self.resizable(0, 0) self.title("* Consultation *") self.mydb = DataBase() self.id_patient = id_patient self.id_medecin = id_medecin frame = Frame(self) frame.pack(expand=1, fill="both", padx=5, pady=5) frame_left = Frame(frame) frame_left.pack(expand=1, fill="y", side="left", padx=5, pady=5, ipadx=5) frame_right = Frame(frame) frame_right.pack(expand=1, fill="y", side="right", padx=5, pady=5, ipadx=5) lb = Label(frame_left, text="Taille", font=FONT, bg="#c7e0f7", fg="#05f") lb.pack(expand=1, fill="x", ipadx=5, ipady=5) self.var_taille = StringVar() self.champ_taille = Entry(frame_left, font=FONT, relief="sunken", textvariable=self.var_taille, bg="#eee", justify="center") self.champ_taille.pack(expand=1, fill="x", ipadx=5, ipady=5) lb = Label(frame_left, text="Temperature", font=FONT, bg="#c7e0f7", fg="#05f") lb.pack(expand=1, fill="x", ipadx=5, ipady=5, pady="5 0") self.var_temp = StringVar() self.champ_temp = Spinbox(frame_left, state="readonly", justify="center", font=FONT, relief="flat", textvariable=self.var_temp, bg="#eee", from_=20, to=40) self.champ_temp.pack(expand=1, fill="x", ipadx=5, ipady=5) lb = Label(frame_left, text="Group sanguin", font=FONT, bg="#c7e0f7", fg="#05f") lb.pack(expand=1, fill="x", ipadx=5, ipady=5, pady="5 0") self.var_grpsang = StringVar() self.champ_grpsang = Combobox(frame_left, font=FONT, justify="center", state="readonly", textvariable=self.var_grpsang, values=[ "A", "A+", "A-", "B", "B+", "B-", "AB", "AB+", "AB-", "O", "O+", "O-" ]) self.champ_grpsang.pack(expand=1, fill="x", ipadx=5, ipady=5) self.var_grpsang.set("A+") lb = Label(frame_right, text="Diagnostique", font=FONT, bg="#c7e0f7", fg="#05f") lb.pack(expand=1, fill="x", ipadx=5, ipady=5) self.champ_diagn = Text(frame_right, font=FONT, relief="sunken", bd=5, height=9, bg="#eee") self.champ_diagn.pack(expand=1, fill="both") btn_frame = Frame(self) btn_frame.pack(expand=1, fill="both", padx=5, pady="0 5") btn1 = Button(btn_frame, text="Annuler", font=FONT, relief="sunken", command=self.destroy) btn1.pack(expand=1, padx=5, ipadx=5, ipady=5, side="left") btn2 = Button(btn_frame, text="Continuer", font=FONT, relief="sunken", command=self.continuer) btn2.pack(expand=1, padx=5, ipadx=5, ipady=5, side="right") self.champs_list = [ self.champ_taille, self.champ_temp, self.champ_grpsang ]
myComm.__name__ = name return myComm # 1 from discord.ext import commands log = logging.getLogger("Rotating Log") load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') passwd = os.getenv('passwd') dbname = os.getenv('dbname') username = os.getenv('username') prefix = os.getenv('prefix') dbconn = DataBase(dbname, username, passwd) pg = PluginManager(log, dbconn, prefix) commander = pg.get_plugins() # 2 bot = commands.Bot(command_prefix='!') for (kw, comm) in commander.items(): botcomms = bindfunction(kw, comm) myhelp = getattr(comm, "myhelp", "No help provided") bot.add_command(commands.Command(botcomms, name=kw, help=myhelp)) @bot.event async def on_ready(): #print(f'{bot.user.name} has connected to Discord!') pass
def check_login(name, passwd): db = DataBase() db_passwd = db.get_password(name) if not db_passwd: return False return check_password_hash(db_passwd, passwd)
class vParkApp(MDApp): def build(self): screen = Builder.load_string(screen_helper) self.data_tables = MDDataTable( size_hint=(0.9, 0.6), # name column, width column column_data=[("Particulars", dp(20)), ("Days Left", dp(20))], row_data=[("1. Insurance", ""), ("2. Pollution", ""), ("3. Service", ""), ("4. Driving Licence", "")]) return screen def open_table(self): self.data_tables.open() # Functions to change screens: def ShowProfile(self): self.root.ids.screen_manager.current = 'profile' def ShowHome(self): self.root.ids.screen_manager.current = 'home' def ShowCamera(self): self.root.ids.screen_manager.current = 'camera' def ShowManualEntryScreen(self): self.root.ids.screen_manager.current = 'MEScreen' def ShowInfo(self, data): self.root.ids.screen_manager.current = 'InfoScreen' def ShowCreateAccount(self): self.root.ids.screen_manager.current = 'create' def ShowLogin(self): self.root.ids.screen_manager.current = 'login' def ShowCreate(self): self.root.ids.screen_manager.current = 'create' def callback_for_menu_items(self, *args): toast(args[0]) def show_bottom_sheet(self): self.bottom_sheet_menu = MDGridBottomSheet() data = { "Facebook": "facebook-box", "WhatsApp": "whatsapp", "Telegram": "telegram", "Twitter": "twitter-box", "Gmail": "gmail", "Bluetooth": "bluetooth", } for item in data.items(): self.bottom_sheet_menu.add_item( item[0], lambda x, y=item[0]: self.callback_for_menu_items(y), icon_src=item[1], ) self.bottom_sheet_menu.open() # Function for OCR (bare for now, needs optimisations, work on it after successful apk build) def OCR(self): # create a camera variable camera1 = self.root.ids['cam'] # capture a shot and export to png camera1.export_to_png("IMG.png") # open image in PIL(basically storing image in a variable) img = Image.open('IMG.png') # OCR using pytesseract stored in a variable named 'data' data = pytesseract.image_to_string(img) # Create a dialog to show the 'data' on screen and open the dialog self.ShowInfo(data) print(data) # Manual entry function: def ManualEntry(self): pass db = DataBase("users.txt") email = ObjectProperty(None) password = ObjectProperty(None) def loginBtn(self): if self.db.validate(self.root.ids.email.text, self.root.ids.password.text): self.reset() self.root.ids.screen_manager.current = 'home' else: self.invalidLogin() def createBtn(self): self.reset() self.root.ids.screen_manager.current = "create" def reset(self): self.root.ids.email.text = "" self.root.ids.password.text = "" def invalidLogin(self): self.pop = MDDialog(text='Invalid username or password.', size_hint=(.5, .3)) self.pop.open() def invalidForm(self): self.pop = MDDialog(text='Please fill in all inputs', size_hint=(.8, .3)) self.pop.open() name1 = ObjectProperty(None) email1 = ObjectProperty(None) password1 = ObjectProperty(None) def submit(self): if self.root.ids.name1.text != "" and self.root.ids.email1.text != "" and self.root.ids.email1.text.count( "@") == 1 and self.root.ids.email1.text.count(".") > 0: if self.root.ids.password1 != "": self.db.add_user(self.root.ids.email1.text, self.root.ids.password1.text, self.root.ids.name1.text) self.reset() self.root.ids.screen_manager.current = "home" else: self.invalidForm() else: self.invalidForm() def lost_vehicle(self): pass
# from random import choice # from myQueries import Users_Table from database import DataBase from exercisesApi import * # import password as password # import username data_base = DataBase() def generate_choices(choices): """ :param choices: list containing two strings new workout and existing workout :return: appends choices to a number and value and joins it to choice_result """ choices_result = [] for number, value in enumerate(choices): choices_result.append(f'\n{number}) {value}') return ''.join(choices_result) def show_exercise_options(exercise_options): """ :param exercise_options: generate choices with exercise option :return: displays input and allows input with generate choices and exercise options as the choices """ return input(f"\n\n What is your Exercise choice, If multiple use a comma to separate values. "
class Tasks: current_index_ = 0 all_amount_ = 0 undone_amount_ = 0 current_task_ = Task() db = DataBase() def __init__(self): self.undone_tasks_ = self.db.undone_tasks() self.done_tasks_ = self.db.done_tasks() self.date_ = date.today() def get_current(self): frogs = [] usual = [] if not (self.date_ in self.undone_tasks_): return for i in range(self.current_index_, len(self.undone_tasks_[self.date_])): x = self.undone_tasks_[self.date_][i] if x.is_frog_: frogs.append(x) else: usual.append(x) for i in range(0, self.current_index_): x = self.undone_tasks_[self.date_][i] if x.is_frog_: frogs.append(x) else: usual.append(x) self.undone_amount_ = len(frogs) + len(usual) self.all_amount_ = self.undone_amount_ + ( len(self.done_tasks_[self.date_]) if (self.date_ in self.done_tasks_) else 0) if len(frogs) > 0: self.current_task_ = frogs[len(frogs) - 1] else: self.current_task_ = usual[len(usual) - 1] def done(self): if not (self.date_ in self.done_tasks_): self.done_tasks_[self.date_] = [] self.done_tasks_[self.date_].append(self.current_task_) self.db.add_old_task(self.current_task_) self.db.delete_task(self.current_task_) self.undone_tasks_[self.date_].remove(self.current_task_) self.undone_amount_ -= 1 if not self.undone_tasks_[self.date_]: del self.undone_tasks_[self.date_] def delete(self, task): self.db.delete_task(task) self.undone_tasks_[task.date_].remove(task) if not self.undone_tasks_[task.date_]: del self.undone_tasks_[task.date_] def skip(self): # false if frog, true otherwise if self.current_task_.is_frog_: return False self.current_index_ += 1 self.current_index_ %= len(self.undone_tasks_[self.date_]) def add(self, task): # adds a new task in our database self.db.add_new_task(task) if task.date_ not in self.undone_tasks_: self.undone_tasks_[task.date_] = [] self.undone_tasks_[task.date_].append(task)
from selenium import webdriver from selenium.webdriver.common.by import By import openpyxl import datetime import valid from valid import Valid from database import DataBase validater = Valid() database = DataBase(user, password, host, db) user = '******' password = '******' host = 'localhost' db = 'kancho_news' today = datetime.date.today() day = today.day month = today.month year = today.year yymmdd = str(format(valid.today, '%Y%m%d')) wb = openpyxl.load_workbook("官庁URL.xlsx") ws = wb["Sheet1"] def store_list_for_xl(candd): list_for_xl.append(candd) return list_for_xl url_list = []
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.constants import g from database import DataBase def flugparabel(t, alpha, v0): x = v0 * np.cos(alpha) * t y = v0 * np.sin(alpha) * t - (g / 2) * t**2 return x, y df = DataBase() fig = plt.figure(1) for index, flug in df.iterrows(): plt.plot(*flugparabel(np.linspace(0, flug["Zeit"], 200), flug["Winkel"], flug["v0"]), label=index) plt.xlabel(r"Weite/$m$") plt.ylabel(r"Höhe/$m$") plt.legend() # plt.show() # plt.savefig("2019-04-12.svg") plt.clf() ax = fig.add_subplot(111, projection='3d') ax.plot(df["Druck"], df["Wasser"], np.sqrt(df["Weite"]**2 / 4 + df["Höhe"]**2), ".") ax.set_xlabel("Druck") ax.set_ylabel("Wasser") ax.set_zlabel("Abstand")
# scrollable_label.update_alert_history(alarm_figure) # was self.scroll_label self.output_content.append(alarm_figure) self.alert_symbol_log.append(self.alert_symbol) # scrollable_label.text += alarm_figure self.new_alerts_scrollable_label.text += alarm_figure print(self.output_content, self.alert_symbol_log) else: print("not working") def reset(self): self.alarm_textinput.text = "" def on_text(self, value, second_value): try: self.user_price = int(second_value) except: print(second_value) # just for debugging db = DataBase("alerts.txt") class CryptoApp(App): def build(self): return MainPage() if __name__ == '__main__': CryptoApp().run()
import os import json import logging import hashlib from flask_cors import CORS from flask import Response, jsonify, send_from_directory, render_template, request, Flask, send_file from flask import flash, redirect, url_for from metaphone import doublemetaphone from werkzeug.utils import secure_filename from database import DataBase from ffprobe import Ffprobe from tools.passwd import hash_password, verify_password, rand_hash HOME_DIR = os.path.dirname(os.path.realpath(__file__)) DB = DataBase(scheme=os.path.join(HOME_DIR, 'mods.sql'), basefile=os.path.join(HOME_DIR, 'data.sqlite')) STATIC_DIR = os.path.join(HOME_DIR, '..', 'web', 'build') UPLOAD_FOLDER = os.path.join(HOME_DIR, 'storage') TMP_PATH = os.path.join(UPLOAD_FOLDER, 'tmp') MOD_PATH = os.path.join(UPLOAD_FOLDER, 'mods') ALLOWED_EXTENSIONS = set(['mod', 'xm', 'it', 's3m']) logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') log = logging.getLogger('hexound_api') #logging.getLogger("urllib3.connectionpool").setLevel(logging.WARNING) def md5(fname): hash_md5 = hashlib.md5()
DataError_Popup() def DataError_Popup(): DataError_Popup = DataErrorPopup(title="Data inputted incorrectly", size_hint=(None, None), size=(400, 400)) DataError_Popup.open() class WindowManager(ScreenManager): pass scrn_manager = WindowManager() db = DataBase("logins.txt") scrn_manager = WindowManager() screens = [SignInPage(name="SignInPage"), InventoryPage(name="InventoryPage")] for screen in screens: scrn_manager.add_widget(screen) scrn_manager.current = "SignInPage" class SigninApp(App): def build(self): return scrn_manager
def __init__(self): self.books_lib = BooksLibrary() self.db = DataBase() pass
from database import DataBase DB = DataBase() # 用户数据库 class User(): def __init__(self, name, score, time): self.name = name self.is_exists_name = False self.score = score self.time = time def user_insert(self): if not self.is_exists_name: r = '''insert into user values(?, ?, ?)''' DB.execute(r, (self.name, self.score, self.time)) DB.save() def user_exists(self): r = '''select * from user where name = ?''' DB.execute(r, (self.name, )) if DB.fetchall(): self.is_exists_name = True def user_delete(self): r = '''delete from user where name = ?''' DB.execute(r, (self.name, )) DB.save() def user_update(self):
if typ != 'OK': print("ERROR on fetch message", email_id) return decoded_mge = email_data[0][1].decode('utf-8') msg = email.message_from_string(decoded_mge) msg_data = dict() msg_data['id'] = int(email_id) msg_data['subject'] = msg['Subject'] msg_data['from'] = msg['From'] date_tuple = email.utils.parsedate_tz(msg['Date']) if date_tuple: local_date = datetime.datetime \ .fromtimestamp(email.utils.mktime_tz(date_tuple)) msg_data['date'] = local_date.strftime("%a, %d %b %Y %H:%M:%S") result.append(msg_data) M.logout() return result SEARCH_CRITERIA = '(OR SUBJECT Devops BODY Devops)' data = get_emails_data( IMAP_SERVER, EMAIL_ACCOUNT, getpass(), # Input for gmail email account pwd SEARCH_CRITERIA) db = DataBase('mysql://{}:{}@127.0.0.1:3306/{}'.format(DB_USERNAME, DB_PASSWORD, DB_NAME)) db.create_table('emails_data', TABLE_SPEC) db.insert_data('emails_data', data, TABLE_SPEC)
import telebot import schedule from markdown import Markdown from config import * from animals_in_game import * from database import DataBase from time import sleep bot = telebot.TeleBot(TOKEN) db = DataBase() class Functions: #Обрабатывает нажатие на кнопку покупки def action_after_purchase(event, animal, user_id, chat_id): if db.take_balance(user_id) >= animal.price: db.minus_balance(user_id, animal.price) db.add_animal(user_id, str(animal.english_name) + '_count') bot.send_message(chat_id, '🎉 *Ура!*\n\n' 'Поздравляем тебя с приобритением нового животного.', parse_mode = 'Markdown' ) else: bot.send_message(chat_id, '🤔*Хм...*\n\n' 'Кажется вам не хватает денег для покупки этого животного.\n' f'*{animal.name}* стоит *{animal.price}* 💰, а у вас на счету всего *{db.take_balance(user_id)}* 💰',
from database import DataBase DB = DataBase( host="", # your host, usually localhost user="******", # your username passwd="", # your password db="crypto") # name of the data base QUERIES = [] for item in QUERIES: DB.run_command(QUERIES)
def setUp(self): try: os.remove(temp_database) # ensure it is not there except OSError: pass self.tmp_db = DataBase(temp_database)