コード例 #1
0
def save_table_to_db(table):
    db_mgr = DBManager()
    array = []
    for row in table:
        fr = int(row['fr'])
        to = int(row['to'])
        re = row['result']
        if isinstance(re, unicode):
            # re.replace(u"\u2018", "'").replace(u"\u2019", "'")
            re = str(re.encode(encoding='utf-8', errors='replace'))

        print('type of re in db saving is: ' + str(type(re)))
        re = re.lower()
        ide = row['identifier']

        if isinstance(ide, unicode):
            ide = str(ide.encode(encoding='utf-8', errors='replace'))
        leads_to = None
        try:
            leads_to = row['leads_to']
        except KeyError:
            pass
        array.append({
            'identifier': ide,
            'fr': fr,
            'to': to,
            're': re,
            'table': row['table_name'],
            'leads_to_table': leads_to
        })

    db_mgr.fuzion_tables.add_many((array))
コード例 #2
0
def main():
    db = DBManager()
    db.create_tables()
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary

    updater = Updater(token, use_context=True)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))
    dp.add_handler(CommandHandler("max_quality", set_max_quality))
    dp.add_handler(CommandHandler("min_quality", set_min_quality))

    # on noncommand i.e message - echo the message on Telegram
    dp.add_handler(MessageHandler(Filters.text, download_video))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()
コード例 #3
0
 def save(self, actor_name, actor_role):
     db_mgr = DBManager()
     db_mgr.table_primary_stats.save_character(character_name=actor_name, role=actor_role,
                                               intelligence=self.intelligence, reflexes=self.reflexes,
                                               technique=self.technique, dexterity=self.dexterity,
                                               presense=self.presense, willpower=self.willpower,
                                               constitution=self.constitution, strength=self.strength,
                                               body=self.body, move=self.move)
コード例 #4
0
 def start(self):
     db = DBManager(self.filename)
     self.combo['values'] = ()
     for row in db.get_tables_names():
         self.combo['values'] += row
     self.combo.current(0)
     cols = db.get_columns_names(self.combo.get())
     curs = db.get_rows(self.combo.get())
     self.tree_update(curs, cols)
コード例 #5
0
ファイル: async_core.py プロジェクト: mom1/messager
 def run(self):
     self.database = DBManager('client')
     self.notify('init_db')
     try:
         asyncio.run(self.async_start())
     except Exception as e:
         logger.error(e, exc_info=True)
         # import ipdb; ipdb.set_trace()
         self.notify('fail', msg=str(e))
コード例 #6
0
ファイル: models.py プロジェクト: Krypticdator/FSTTRPGTables
 def load(self, name):
     db_mgr = DBManager()
     table = None
     if db_mgr.fuzion_tables.count_options(name) > 0:
         table = db_mgr.fuzion_tables.get_table(name)
     else:
         table = utilities.get_aws_table(name)
         utilities.save_table_to_db(table)
         table = db_mgr.fuzion_tables.get_table(name)
     if table is not None:
         for row in table:
             self.add_option(row.fr, row.to, row.re, leads_to=row.leads_to_table, identifier=row.identifier)
コード例 #7
0
    def tree_update(self, cursor, columns):
        db = DBManager(self.filename)
        for i in self.tree.get_children():
            self.tree.delete(i)
        self.tree['show'] = 'headings'
        self.tree['columns'] = ()
        self.tree['columns'] = tuple(columns)
        for col in columns:
            self.tree.column(col, stretch=False, width=100)
            self.tree.heading(col, text=col)

        for row in cursor:
            self.tree.insert('', 'end', values=row)
コード例 #8
0
 def load(self, actor_name, actor_role):
     db_mgr = DBManager()
     stats = db_mgr.table_primary_stats.get_character(actor_role, actor_name)
     self.intelligence = stats.intelligence
     self.reflexes = stats.reflexes
     self.technique = stats.technique
     self.dexterity = stats.dexterity
     self.presense = stats.presense
     self.willpower = stats.willpower
     self.constitution = stats.constitution
     self.strength = stats.strength
     self.body = stats.body
     self.move = stats.move
コード例 #9
0
 def save_changes(self):
     db = DBManager(self.filename)
     table = self.combo.get()
     db.query("DELETE FROM {}".format(table))
     cols = str(self.tree['columns'])[1:-1]
     columns = "(" + cols + ")"
     values = ''
     for i in self.tree.get_children():
         vals = str(self.tree.item(i)['values'])[1:-1]
         values += "(" + vals + "), "
     query = "INSERT INTO {} {} VALUES {}".format(table, columns,
                                                  values[:-2])
     db.query(query)
コード例 #10
0
    def __init__(self):
        self._api = VKApi(VK_USER, VK_PASSWORD, version=API_VERSION)
        self._user = self.get_user()
        self._user_id = self._user['id']

        self._db = DBManager()

        self._commands = {
            'cancel': self.cancel,
            'publish': self.publish,
            'delayed_publish': self.delayed_publish
        }

        print "[INFO] Logged in as %s %s (UID: %s)" % (
            self._user['first_name'], self._user['last_name'], self._user_id)
コード例 #11
0
ファイル: main.py プロジェクト: jalspons/xxl_campaign_sniffer
def update():
    # Start logging
    init_logging()
    # Create dbmanager and httpclient
    db_client = DBManager(db_file, db_logger_name)
    http_client = HttpClient(host, url_paths, http_logger_name)
    
    # Create db if not existing
    if db_client.is_empty():
        db_client.create_db()

    #print(db_client.fetch_products_from_db())
    
    for product_group, url_path in url_paths.items():
        html_file = http_client.fetch_html_file(host, url_path)
        json_file = http_client.parse_html_file(html_file)
        
        db_client.add_products(product_group, json_file)
コード例 #12
0
 def run_sql(self):
     query = self.entry.get()
     db = DBManager(self.filename)
     try:
         curs = db.query(query)
         cols = list(map(lambda x: x[0], curs.description))
         self.tree_update(curs, cols)
     except Exception as e:
         self.error_window = Toplevel(self.master)
         self.error_window.grab_set()
         self.error_window.title('Что-то пошло не так :(')
         self.error_window.minsize(320, 48)
         self.error_window.resizable(0, 0)
         label = ttk.Label(self.error_window, text=e)
         label.pack(side="top", fill="both", padx=5, pady=5)
         ok = ttk.Button(self.error_window,
                         text='Ок',
                         command=self.error_window.destroy)
         ok.pack(side="right", padx=5, pady=5)
コード例 #13
0
def download_video(update, context):
    db = DBManager()
    url = update.message.text
    chat_id = update.message.chat_id
    quality = db.get_chat_quality(chat_id)
    username = str(update.message.from_user.username)
    if is_url(url) is False:
        update.message.reply_text('Enter Url please')
        return

    file_id = db.get_url_file_id(url, quality)
    if file_id:
        update.message.reply_audio(file_id)
        db.insert_user_request(url, username)
        context.bot.send_message(chat_id=owner_chat_id,
                                 text=TELEGRAM_LOG.format(username, url))
        return
    try:
        meta = downloader.download_video(url, quality)
    except youtube_dl.utils.DownloadError as e:
        update.message.reply_text(str(e))
        return
    audio_file = open(meta.file_name, 'rb')
    cover = open(meta.cover, 'rb')
    response = update.message.reply_audio(
        audio_file,
        title=meta.meta.get('title', None),
        performer=meta.meta.get('uploader', None),
        duration=meta.meta.get('duration', None),
        caption=meta.meta.get('title', None),
        thumb=cover)
    context.bot.send_message(chat_id=owner_chat_id,
                             text=TELEGRAM_LOG.format(username, url))

    db.insert_file_id(url, response['audio']['file_id'], quality)
    db.insert_user_request(url, username)

    os.remove(meta.file_name)
    os.remove(meta.cover)
コード例 #14
0
    def load(self, tablename):
        self.name = tablename
        print(tablename)
        db_mgr = DBManager()

        if db_mgr.fuzion_tables.count_options(tablename) > 0:
            pass
        else:
            t = utilities.get_aws_table(tablename)
            utilities.save_table_to_db(t)
        t = db_mgr.fuzion_tables.get_table(tablename)
        for row in t:
            option = TraitsTableOption()
            option.fr = int(row.fr)
            option.to = int(row.to)

            option.re = str(row.re)

            option.identifier = str(row.identifier)
            leads_to = ""
            if row.leads_to_table is not None:
                leads_to = row.leads_to_table
            option.leads_to = leads_to
            self.options.append(option)
コード例 #15
0
def start(update, context):
    db = DBManager()
    db.create_new_user(update.message.chat_id)
    """Send a message when the command /start is issued."""
    update.message.reply_text(
        'Hi! This is yputube downloader bot. Enter a link to download video.')
コード例 #16
0
ファイル: update_library.py プロジェクト: hchen13/hashnet
            ssh_private_key = '/home/ethan/.ssh/mac_id_rsa'
        else:
            ssh_private_key = '/Users/ethan/.ssh/id_rsa'
        server = SSHTunnelForwarder(
            ("121.41.12.158", 22),
            ssh_username='******',
            ssh_pkey=ssh_private_key,
            remote_bind_address=(
                db_params['host'],
                3306
            )
        )
        server.start()
        db_params['host'] = server.local_bind_host
        db_params['port'] = server.local_bind_port
    db = DBManager(**db_params)
    storage = Storage(**oss_params)
    hashnet = Hashnet()
    hashnet.load()

    print("Scanning database for images not being processed...")
    session = db.Session()
    results = session.query(Image).filter(
        or_(
            Image.features == None,
            Image.hash == None
        )
    ).all()
    n = len(results)
    print("Scanning complete! {} in total.\n".format(n))
コード例 #17
0
ファイル: spill.py プロジェクト: aniket-bhange/spillwater
 def getAll(self):
     db = DBManager()
     db.connect()
     units = db.find_all()
     return units
コード例 #18
0
ファイル: init.py プロジェクト: t-8ch/alot
    try:
        if not alotconfig:
            alotconfig = configfiles[0]
            settings.write_default_config(alotconfig)

        settings.read_config(alotconfig)
        settings.read_notmuch_config(notmuchconfig)
    except (ConfigError, OSError, IOError), e:
        sys.exit(e)

    # store options given by config swiches to the settingsManager:
    if args['colour-mode']:
        settings.set('colourmode', args['colour-mode'])

    # get ourselves a database manager
    dbman = DBManager(path=args['mailindex-path'], ro=args['read-only'])

    # determine what to do
    try:
        if args.subCommand == 'search':
            query = ' '.join(args.subOptions.args)
            cmdstring = 'search %s %s' % (args.subOptions.as_argparse_opts(),
                                          query)
            cmd = commands.commandfactory(cmdstring, 'global')
        elif args.subCommand == 'compose':
            cmdstring = 'compose %s' % args.subOptions.as_argparse_opts()
            cmd = commands.commandfactory(cmdstring, 'global')
        else:
            default_commandline = settings.get('initial_command')
            cmd = commands.commandfactory(default_commandline, 'global')
    except CommandParseError, e:
コード例 #19
0
ファイル: spill.py プロジェクト: aniket-bhange/spillwater
 def saveValue(self, data):
     db = DBManager()
     db.connect()
     data['waterunit'] = str(self.unit)
     data['totalunit'] = str(self.totalUnit)
     return db.save(data)
コード例 #20
0
        presense = self.stats.presense
        strength = self.stats.strength
        constitution = self.stats.constitution
        willpower = self.stats.willpower
        body = self.stats.body
        move = self.stats.move
        packed_stats = {'int':intelligence, 'ref':reflexes, 'tech':technique, 'dex':dexterity, 'pre':presense,
                        'str':strength, 'con':constitution, 'will':willpower, 'body':body, 'move':move}
        models.upload_to_aws(name=name, role=role, packed_stats=packed_stats)
        db_mgr = DBManager()
        db_mgr.table_primary_stats.save_character(character_name=name, role=role, intelligence=intelligence,
                                                  reflexes=reflexes, technique=technique, dexterity=dexterity,
                                                  presense=presense, strength=strength, constitution=constitution,
                                                  willpower=willpower, body=body, move=move)'''


    view = View(
        Item('character_name', style='custom', show_label=False),

        Item('stats', style='custom'),
        Item('save', show_label=False),
        Item('load', show_label=False)

        # Item('upload', show_label=False)
    )

if __name__ == '__main__':
    s = StandaloneContainer()
    db_mgr = DBManager()

    s.configure_traits()
コード例 #21
0
 def __init__(self):
     self.hashnet = Hashnet()
     self.hashnet.load()
     self.db = DBManager(**db_params)
コード例 #22
0
 def __init__(self):
     self.bot = TeleBot(self.token)
     logger.setLevel(logging.INFO)  # Outputs debug messages to console.
     self.db = DBManager()
     self.handler = Handler(self.bot)
コード例 #23
0
def set_max_quality(update, context):
    db = DBManager()
    db.set_chat_settings(update.message.chat_id, 'max')
    update.message.reply_text("Max quality is set")
コード例 #24
0
 def __init__(self):
     self.os    = OpenstackBridge()
     self.db    = DBManager()
コード例 #25
0
 def cmb_update(self, _event):
     db = DBManager(self.filename)
     cols = db.get_columns_names(self.combo.get())
     curs = db.get_rows(self.combo.get())
     self.tree_update(curs, cols)
コード例 #26
0
    def __init__(self, master):
        # Main window
        self.master = master
        self.master.title('Simple DB viewer')
        self.master.minsize(width=640, height=480)

        menubar = Menu(self.master)

        menu = Menu(self.master, tearoff=0)
        menu.add_command(label='Создать базу данных')
        menu.add_command(label='Открыть базу данных')
        menu.add_separator()
        menu.add_command(label='Выход')
        menubar.add_cascade(label='Файл', menu=menu)

        menu = Menu(self.master, tearoff=0)
        menu.add_command(label='Записать изменения')
        menu.add_command(label='Удалить изменения')
        menubar.add_cascade(label='База данных', menu=menu)

        self.master.config(menu=menubar)


        tree_frame = ttk.Frame(self.master)
        btns_frame = ttk.Frame(self.master)

        # Connect to DB
        self.db = DBManager('db-name')

        # Combobox with select of table
        self.combo = ttk.Combobox(btns_frame)
        self.combo['values'] = ()
        for row in self.db.get_tables_names():
            self.combo['values'] += row
        self.combo.current(0)
        self.combo.bind('<<ComboboxSelected>>', self._combo_update)

        self.tree = ttk.Treeview(tree_frame, selectmode='extended')
        tree_x_scroll = ttk.Scrollbar(tree_frame, orient='hor', command=self.tree.xview)
        tree_y_scroll = ttk.Scrollbar(tree_frame, orient='vert', command=self.tree.yview)
        self.tree.configure(yscrollcommand=tree_y_scroll.set)
        self.tree.configure(xscrollcommand=tree_x_scroll.set)

        tree_y_scroll.pack(side='right', fill='y')
        self.tree.pack(side='top', fill='both', expand=True)
        tree_x_scroll.pack(side='bottom', fill='x')

        self._combo_update()

        # Buttons
        add = ttk.Button(btns_frame, text='Добавить запись')
        rm = ttk.Button(btns_frame, text='Удалить запись')
        run_sql = ttk.Button(btns_frame, text='Выполнить SQL')

        # Packs all elements
        tree_frame.pack(side='top', fill='both', expand=True)
        btns_frame.pack(side='bottom', fill='both')
        self.combo.pack(side='left', padx=5, pady=5)
        add.pack(side='left', padx=5, pady=5)
        rm.pack(side='left', padx=5, pady=5)
        run_sql.pack(side='left', padx=5, pady=5)
コード例 #27
0
from flask_socketio import SocketIO, emit
from db import DBManager
from datetime import datetime
'''
***************
On RPi
***************
'''
template_dir = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
template_dir = os.path.join(template_dir, 'greenhouse/build')
static_dir = os.path.join(template_dir, 'static')
app = Flask(__name__, template_folder=template_dir, static_folder=static_dir)
socketio = SocketIO(app, async_mode=None)
thread = None
thread_lock = Lock()
users = DBManager('localhost', 27017)
users.set_db('greenhouse')
users.set_collection('users')

secret = None
debug = None
if 'RPi' in os.environ:
    from Adafruit_BME280 import *
    import Adafruit_ADS1x15
    import RPi.GPIO as GPIO
    secret = os.environ['SECRET_KEY']
    app.config['SECRET_KEY'] = secret
    debug = False
else:
    secret = 'lZsY4zEG00QwQzDDKiMrPqsrUcYQhG5Z'
    app.config['SECRET_KEY'] = secret