Exemple #1
0
import pytz
import datetime

from flask import Flask
from os.path import dirname, join, basename, abspath

sys.path.insert(0, dirname(dirname(abspath(__file__))))

from db import DataBase
from blog.blog.utils import project_path

app = Flask(__name__)
app.config.from_pyfile(join(project_path, "settings.py"))
tz = pytz.timezone(app.config.get("TIME_ZONE"))

db = DataBase(app.config)


def retrieve(word, article):
    regex = re.compile(r"\[comment\]: <%s> \((.+?)\)" % word)
    for line in article[:]:
        mth = regex.search(line)
        if mth:
            article.remove(line)
            return mth.group(1)
    return ""


def insert(filename):
    id = time.strftime("%Y%m%d%H%M%S")
    title = basename(filename).replace(".md", "")
from db import DataBase
from PyQt5 import QtCore, QtGui, QtWidgets

db = DataBase("data.db")


class Ui_win(object):
    def setupUi(self, win):
        win.setObjectName("win")
        win.resize(833, 570)
        win.setWindowFlags(QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMinimizeButtonHint)
        self.Fname = QtWidgets.QLabel(win)
        self.Fname.setGeometry(QtCore.QRect(40, 30, 81, 31))
        font = QtGui.QFont()
        font.setFamily("Segoe UI Black")
        font.setPointSize(10)
        font.setWeight(75)
        self.Fname.setFont(font)
        self.Fname.setAutoFillBackground(True)
        self.Fname.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.Fname.setObjectName("Fname")
        self.Sname = QtWidgets.QLabel(win)
        self.Sname.setGeometry(QtCore.QRect(40, 80, 101, 31))
        font = QtGui.QFont()
        font.setFamily("Segoe UI Black")
        font.setPointSize(10)
        font.setWeight(75)
        self.Sname.setFont(font)
        self.Sname.setAutoFillBackground(True)
        self.Sname.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.Sname.setObjectName("Sname")
Exemple #3
0
def before_request():
    g.db = DataBase(**db_info)
    g.db.connect()
 def __init__(self):
     super(KafkaToDB, self).__init__()
     self._db = DataBase()
     self._cache = []
     self._cond = Condition()
     Thread(target=self._ingest).start()
Exemple #5
0
def show_image(imageid):
    database = DataBase(imageid)
    return send_file(
        imageid,
        mimetype='image/gif')  #render_template("image.html",imagename=imageid)
Exemple #6
0
def new_db() -> Generator[DataBase, None, None]:
    db = DataBase()
    for table in db.get_tables_names():
        db.delete_table(table)
    delete_files(DB_ROOT)
    yield db
Exemple #7
0
from tkinter import *
from tkinter import messagebox
from db import DataBase

db = DataBase('store.db')


def populate_list():
    parts_list.delete(0, END)
    for row in db.fetch():
        parts_list.insert(END, row)


def add_item():
    if part_text.get() == '' or customer_text.get() == '' or retailer_text.get(
    ) == '' or price_text.get() == '':
        messagebox.showerror('Required Field', 'Please add all fields.')
        return
    db.insert(part_text.get(), customer_text.get(), retailer_text.get(),
              price_text.get())
    parts_list.insert(END, (part_text.get(), customer_text.get(),
                            retailer_text.get(), price_text.get()))
    clear_text()
    populate_list()


def select_item(event):
    try:
        global select_item
        index = parts_list.curselection()[0]
        select_item = parts_list.get(index)
Exemple #8
0
 def __init__(self):
     super(KvExtension, self).__init__()
     self.subscribe(KeywordQueryEvent, KeywordQueryEventListener())
     self.subscribe(ItemEnterEvent, ItemEnterEventListener())
     self.db = DataBase()
     _LOGGER_.debug("KV Extension DataBase Done")
Exemple #9
0
 def __init__(self, type):
     self.db = DataBase()
Exemple #10
0
def init():
    db = DataBase(**(config['db']))
    miner_type = config['miner_type']

    db_init(db, miner_type)
Exemple #11
0
    def __init__(self, application):
        self.application = application
        self.edit = False
        self.filter = False
        self.locked = True
        self.builder = Gtk.Builder()
        glade_path = "{}/streams.glade".format(path.dirname(__file__))
        self.builder.add_from_file(glade_path)

        self.window = self.builder.get_object("main_win")
        self.window.set_wmclass("Streams", "Streams")
        self.window.set_title("Streams")
        self.window.connect("delete-event", self.exit)

        menu_com = self.builder.get_object("menu_command")
        self.commands_menu = CommandsMenu(self)
        menu_com.set_popup(self.commands_menu)

        events = {
            "on_selection_change": self.on_selection_change,
            "on_activation": self.on_activation,
            "on_add_clicked": self.on_add_clicked,
            "on_edit_clicked": self.on_edit,
            "on_delete_clicked": self.on_delete,
            "on_save_clicked": self.on_save,
            "on_cancel_clicked": self.on_cancel,
            "on_dig_clicked": self.on_dig,
            "on_auto_clicked": self.on_autofill,
            "on_url_change": self.dig_button_state,
            "on_web_change": self.web_button_state,
            "on_web_clicked": self.visit_web,
            "on_menuchoice_save_activate": self.commands_menu.add,
            "on_menuchoice_delete_activate": self.commands_menu.delete,
            "on_command_menu_activated": self.commands_menu.activated,
            "on_menu_item_export_activate": self.on_export,
            "on_menu_item_addurl_activate": self.add_url,
            "on_menu_item_addfold_activate": self.add_folder,
            "on_menu_item_openfile_activate": self.add_file,
            "on_menu_item_export_folder_activate": self.on_export_folder,
            "on_entry_filter_changed": self.filter_change,
            "on_view_bookmarks_drag_drop": self.on_drag_drop,
            "on_menu_item_filter_list_toggled": self.filter_toggle
        }
        self.builder.connect_signals(events)

        self.db = DataBase(str, str, str, str, str, str, str, bool, int)
        self.db.load()
        self.tree_filter = self.db.filter_new(None)
        self.entry_filter = self.builder.get_object("entry_filter")
        self.tree_filter.set_visible_func(self.filter_func)

        self.treeview = self.builder.get_object("view_bookmarks")
        self.treeview.set_model(self.tree_filter)
        self.treeview.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK,
                                               [("list_row", Gtk.TargetFlags.SAME_WIDGET, 0)],
                                               Gdk.DragAction.MOVE)
        self.treeview.enable_model_drag_dest([("list_row", Gtk.TargetFlags.SAME_WIDGET, 0)],
                                             Gdk.DragAction.MOVE)

        self.selection = self.builder.get_object("bookmarks_view_selection")

        self.restore_state()

        self.window.set_application(application)
        self.window.show_all()
        self.locked = False
Exemple #12
0
from messages import *
from db import DataBase
from keyboard import Keyboard
from news import News
from exams_parser import Exam, Themes
import config
from Voting import create_cod, check_mail, send_mail
from db_voit import DataBaseVot
from cod import check_cod, read_cod
"""Initialization"""

exam = Exam()
logging.basicConfig(level=logging.INFO)
bot = Bot(config.TOKEN)
dp = Dispatcher(bot)
Database = DataBase()
Database.init_db()
Vot = DataBaseVot()
Vot.init_db()
keyboard = Keyboard()
news = News('news.txt')
themes = Themes()
"""keybord"""


def number(number):
    try:
        number = int(number)
        return True
    except Exception as e:
        return False
 def __init__(self, app, request, **kwargs):
     super(AnalyticsHandler, self).__init__(app, request, **kwargs)
     self._db = DataBase()
Exemple #14
0
import os
from google import GoogleApi
from db import DataBase
import discord
from dotenv import load_dotenv
from discord.ext import commands

#Create an object of Database
dbOb = DataBase("test.db")

#Load Token from .env file
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

#Create a bot object
bot = commands.Bot(command_prefix='!')


#event when bot gets connected to discord
@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord!')


#event when new member joins the application
@bot.event
async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send(
        f'Hi {member.name}, welcome to my Discord server!')
Exemple #15
0
from aiogram import Bot, Dispatcher, executor, types
from db import DataBase
import settings

# Initialize global vars
db = DataBase("db.db")
bot = Bot(token=settings.bot_api_token)
dispatcher = Dispatcher(bot)


# Inline keyboard for choosing language
langs_panel = types.InlineKeyboardMarkup().add(types.InlineKeyboardButton("Русский", callback_data="rus_lang"),
                                               types.InlineKeyboardButton("English", callback_data="eng_lang"))

# Keyboard for choosing currency
currency_panel = types.ReplyKeyboardMarkup(resize_keyboard=True).add(types.KeyboardButton("$"),
                                                                     types.KeyboardButton("€"),
                                                                     types.KeyboardButton("£"))

# (For admin) Accept user payment
accept_pay_panel = types.InlineKeyboardMarkup().add(types.InlineKeyboardButton("Pay", callback_data="pay_accept"),
                                                    types.InlineKeyboardButton("Cancel", callback_data="pay_cancel"))


# Welcome
@dispatcher.message_handler(commands=["start"])
async def welcome(message: types.Message):
    user_id = message.from_user.id
    if user_id != settings.admin_id:
        if db.user_exists(user_id):
            await message.answer("Hello again!")
Exemple #16
0
import pytest
from db import DataBase
from db_api import DBField, SelectionCriteria, DB_ROOT, DBTable
STUDENT_FIELDS = [DBField('ID', int), DBField('First', str),
                  DBField('Last', str), DBField('Birthday', str)]

db = DataBase()


def create_students_table(db: DataBase, num_students: int = 0) -> DBTable:
    table = db.create_table('Students_index', STUDENT_FIELDS, 'ID')
    for i in range(num_students):
        add_student(table, i)
    return table


def add_student(table: DBTable, index: int, **kwargs) -> None:
    info = dict(
        ID=1_000_000 + index,
        First=f'John{index}',
        Last=f'Doe{index}',
        Birthday="23/11/2000"
    )
    info.update(**kwargs)
    table.insert_record(info)


def test_create_index():
    Students_index = create_students_table(db)
    assert db.num_tables() == 1
    assert db.get_tables_names() == ['Students_index']
Exemple #17
0
from flask import Flask, request, render_template, redirect, flash, jsonify, url_for
import pandas as pd
import numpy as np
from surprise import dump
from db import DataBase
from recommender import Recommender

ITEMS = 50
app = Flask(__name__)
users = np.load('data/users.npy').item()

db = DataBase(users, pd.read_csv('data/attractions.csv', index_col='index'),
              pd.read_csv('data/ratings_reshaped.csv'),
              dump.load('data/funksvd')[1])
recommender = Recommender(db)
attractions = db.get_attractions()
topics = [{
    'id': '0',
    'name': 'Landmarks',
    'photo': '/static/landmarks.jpg'
}, {
    'id': '1',
    'name': 'Art',
    'photo': '/static/art.jpeg'
}, {
    'id': '2',
    'name': 'Tours',
    'photo': '/static/tours.jpg'
}, {
    'id': '3',
    'name': 'Food',
import tkinter as tk
from db import DataBase

db = DataBase('shelf.db')


class BookManager:
    def __init__(self, root):
        self.root = root
        self.root.title('Book Manager')
        self.root.geometry('600x600')

        self.create_widgets()
        self.selected_item = 0
        self.populate_list()

    def create_widgets(self):
        self.name = tk.StringVar()
        self.author = tk.StringVar()

        # head
        self.hframe = tk.Frame(self.root)
        self.lName = tk.Label(self.hframe, text='Name')
        self.eName = tk.Entry(self.hframe, textvariable=self.name)
        self.lAuthor = tk.Label(self.hframe, text='Author')
        self.eAuthor = tk.Entry(self.hframe, textvariable=self.author)
        self.bAddBook = tk.Button(self.hframe,
                                  text='Add',
                                  command=self.add_book)
        self.bDeleteBook = tk.Button(self.hframe,
                                     text='Delete',
Exemple #19
0
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

from parsel import Selector
from selenium.webdriver.support.ui import Select
import pandas as pd
from bs4 import BeautifulSoup
from time import sleep
import os
import hashlib
import sys
sys.path.append('..')
#Connect to database

from db import DataBase
db = DataBase('../newsdata.sqlite')
conn = db.create_connection()

insert_record_sql = """ INSERT OR IGNORE INTO news (id, url) VALUES(?, ?)"""
# Insert new record into table
#Open web browsers
driver = webdriver.Chrome('D:/chromedriver')

driver.get('https://tinnhanhchungkhoan.vn/')
stock_market_topic = driver.find_element_by_xpath('//*[@id="gc1"]').click()

for i in range(100):
    sleep(10)
    urls = driver.find_elements_by_xpath('//*[@id="listing-zone-ajax"]//a')
    next_button = driver.find_elements_by_xpath(
        '//*[@class="btn btn-primary"]')
Exemple #20
0
#!/usr/bin/python3.6
# -*- coding: utf-8 -*-

# СОЗДАТЬ БД ДЛЯ БОТА

from db import DataBase

db = DataBase("students.db")
db.execute("DROP TABLE IF EXISTS STUDENTS")
db.execute("DROP TABLE IF EXISTS PENDING")
db.execute("DROP TABLE IF EXISTS GAMEMAZE")
db.execute("DROP TABLE IF EXISTS TAGS")
db.execute("DROP TABLE IF EXISTS SUBSCRIBES")

# Students
# current_keyboard устарел, надо избавиться
db.execute("""
    CREATE TABLE Students (
        user_id INTEGER NOT NULL PRIMARY KEY UNIQUE,
        full_name TEXT,
        code TEXT,
        current_keyboard TEXT);
""")

# Pending
db.execute("""
    CREATE TABLE Pending (
        user_id INTEGER NOT NULL PRIMARY KEY UNIQUE,
        act TEXT,
        FOREIGN KEY(user_id) REFERENCES students(user_id));
""")
Exemple #21
0
# -*- coding: utf-8 -*-
import config
from re import *
from db import DataBase
from states import State
import functions as func
from telebot import types
import mail

db = DataBase(config.db_path, config.db_file)


class Message:
    def __init__(self, bot):
        self.bot = bot

    def get_email_input(self, message):
        """
        Обрабатываем и возвращаем стартовое сообщение
        """
        self.bot.send_message(
            message.chat.id,
            func.message_wrapper({
                'headline':
                'Ввод email',
                'text':
                'Для того, чтобы мы могли Вам ответить, введите Ваш email:'
            }),
            parse_mode="HTML")

    def get_choice_menu(self, message):
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

from db import DataBase, get_xlsx_path, get_dbauth_file_path
import openpyxl

file_xlsx = get_xlsx_path()
connect_file = get_dbauth_file_path()

wb = openpyxl.load_workbook(filename=file_xlsx)
ws = wb.active

db = DataBase(connect_file)
for row in range(2, ws.max_row + 1):
    description = ws.cell(row=row, column=db._find_column(ws,
                                                          'Description')).value
    films_id = ws.cell(row=row, column=db._find_column(ws, 'ID')).value
    sql_request = f"UPDATE films SET description=%s WHERE id=%s;"
    param = (description, films_id)
    db.request(sql_request, param)
wb.close()
db.close()
Exemple #23
0
     'Введите букву диска для записи на видеосервер: ').upper() + ':'
 work_paths = (os.path.join(arc_disk,
                            r'\Convert'), os.path.join(arc_disk, r'\New'))
 with KinopoiskParser() as browser:
     browser.open_selenium()
     for work_path in work_paths:  # проверяем существуют ли указанные рабочие пути
         print("=" * 150)
         if path_existence_check(work_path):
             for adress, dirs, files in os.walk(work_path):
                 if adress == work_path:  # если находимся в корне рабочего пути, то обрабатываем все фильмы
                     for file in files:
                         film = Film(file, adress, serv_disk, chief_disk)
                         if film.copy_to_servdisk():
                             browser.write_data(
                             )  # находим и дописываем данные с Кинопоиска
                             with DataBase(CONNECT_FILE
                                           ) as base:  # запись в Postgresql
                                 base.query()
                         film.copy_to_chiefdisk()
                         print("=" * 150)
                 elif not dirs:  # если не в корне - значит это сериал. Запись происходит когда уже в папке с сериями
                     serial = Serial(files, adress, serv_disk, chief_disk)
                     if serial.copy_to_servdisk():
                         browser.write_data(
                         )  # находим и дописываем данные с Кинопоиска
                         with DataBase(CONNECT_FILE
                                       ) as base:  # запись в Postgresql
                             base.query()
                     print("-" * 150)
                     serial.copy_to_chiefdisk()
                     print("=" * 150)
         else: