Example #1
0
 def __init__(self, repository, mountpoint):
     # TODO: add routine to automatically fill the DB with data if
     # empty.  Should probably require us to run the program with
     # some switch
     sql.init(repository)
     self.repository = repository
     self.mountpoint = mountpoint
Example #2
0
def register():
    print("=======================================")
    print("********** Register *******************")
    print("========================================")
    first_name = input("Please enter your first name: \n")
    last_name = input("Enter your last name: \n")
    email = input("Enter your email: \n")
    password = getpass("Enter your password: \n")
    balance = 0
    account_number = account.generating_account_db()
    sql.init()
    is_user_created = sql.insert_details(account_number, first_name, last_name,
                                         email, password, balance)

    if is_user_created:
        loading.load()
        print("=======================================")
        print("Registration Successful")
        print("========================================")
        print(f"Your account number is : {account_number}")
        print(
            f"{first_name} {last_name}, your account has been successful created!",
            sep=" ")
        print("You can now login")
        login()
    else:
        print("Something went wrong, please try again!")
        loading.load()
        register()
Example #3
0
async def on_ready():
    print(f'{c.bot.user.name} has connected to Discord!')
    db.init(SQLITEFILE)

    guild = discord.utils.get(c.bot.guilds, name=GUILD)
    print(f'{c.bot.user} is connected to the following guild:\n'
          f'{guild.name}(id: {guild.id})')
    async for guild in c.bot.fetch_guilds(limit=150):
        print(guild.name)
def stream():
    current_track = None

    while 1:
        query = u'''
            select
                id,
                artist,
                title,
                duration
            from blog_audio
            where radio = 1
            order by id desc
            limit %d
        ''' % radiolimit

        sql.init()
        sql.cur.execute(query)
        plist = sql.cur.fetchall()

        id = 0
        for track in plist:
            if current_track is None or track[0] < current_track[0]:
                current_track = track
                break
            id += 1
        if id >= radiolimit:
            current_track = plist[0]

        path = os.path.join(datadir, str(current_track[0]) + '.mp3')
        name = '%s - %s' % (current_track[1], current_track[2])

        if path[:7] == 'http://':
            r = urllib.urlopen(path)
            meta = r.info()
            bufsize = meta.getheaders("Content-Length")[0]
            bufsize = int(bufsize)
        else:
            r = open(path)
            stat = os.stat(path)
            bufsize = stat.st_size

        bufsize = bufsize / track[3]
        bufsize = int(bufsize * sleeptime) + 100

        buf = r.read(bufsize)
        
        while buf != '':
            for port in ports:
                s.sendto(buf, (host, port))
            buf = r.read(bufsize)
            sleep(sleeptime)

        r.close()
        sleep(sleeptime)
Example #5
0
def main():
    db = sql.init()
    # with open('sqw.csv', 'w', newline='') as csv_file:
    #     writer = csv.writer(csv_file)
    #     writer.writerow(['公司名称', '地址', '电话', '传真', '手机', '网址', '邮箱', '联系人', '公司人数', '注册资金', '经济类型', '公司产品', '公司简介'])
    detail_urls = get_all_detail_url(home_page_url)
    # 遍历所有的城市
    for url in detail_urls:
        print('下载', url)
        part_url = get_part_url(url)
        # 遍历所有的分类
        for part in part_url:
            print('分类信息', part)
            corp_url = get_url_of_corp(part)
            # 遍历所有的企业
            for corp in corp_url:
                print('公司链接', corp)
                detail = parser_detail(get_html(corp), db)
                time.sleep(1)
Example #6
0
from bs4 import BeautifulSoup
#from fake_useragent import UserAgent
from user_agent import generate_user_agent
import gen as Gen
import get as Get
import sql, search, config

#Initialize
#ua = UserAgent().random
ua = generate_user_agent()
regDic = {}

#SQL
db_name = "%s\\%s.db" % (config.LogPath, config.LogName
                         ) if config.LogPath else config.LogName + ".db"
sql.init(db_name, "Movie")
sql.init(db_name, "TV")

with open("folder.txt", "r", encoding='utf-8-sig') as data:  #只在這些子資料夾執行
    folderList = [l.strip() for l in data]
with open("region.txt", "r", encoding='utf-8-sig') as regdata:  #地區縮寫對應
    regList = [l.strip().split(',') for l in regdata]
for reg in regList:
    regDic[reg[0]] = reg[1:]


#Function
def resjson(url):
    r = requests.get(url, headers={'User-Agent': ua})
    res = r.json()  # return dict
    return res
Example #7
0
        self.label_14.setText(_translate("MainWindow", str(dist)))
        self.label_19.setText(_translate("MainWindow", str(time_delta)))
        self.label_9.setText(_translate("MainWindow", src + '-' + trans_city))
        self.label_10.setText(_translate("MainWindow",
                                         trans_city + '-' + dest))
        self.set_table_content(self.tableWidget, train1)
        self.set_table_content(self.tableWidget_2, train2)

    def print_all_res_list(self):
        print(self.all_list)

    def printzhishiku(self):
        # QtWidgets.QMessageBox.about(None, '全国铁路枢纽站列表', str(major_station))
        fm = QtWidgets.QMainWindow()
        f = Ui_Form()
        f.setupUi(fm)
        fm.show()
        # f.setContent(str(major_station))


if __name__ == '__main__':
    sql.init()
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
    sql.close()
Example #8
0
    print('user.NickName:', user.NickName)
    if user.Sex == 1:
        user_sex = "男"
        print('user.Sex:', '男')
    elif user.Sex == 2:
        user_sex = "女"
        print('user.Sex:', '女')
    else:
        user_sex = "未知"
        print('user.Sex:', '未知')
    print('user.Province:', user.Province)
    print('user.City:', user.City)
    print('user.Signature:', user.Signature)
    # 插入数据库
    try:
        conn = sql.init()
        sql.insert_friends(conn, user.NickName, user_sex, user.Province,
                           user.City, user.Signature)
        sql.finish(conn)
    except Exception as e:
        print(e)

# 好友数量
number_of_friends = len(friends)

# pandas可以把据处理成DataFrame
df_friends = pandas.DataFrame(friends)

# 获取性别信息:男性为1、女性为2、未知为0
Sex = df_friends.Sex
Example #9
0
from flask import Flask
from flask import request
import sql

app = Flask(__name__)
sql.register_close(app)
sql.init(app)

@app.route('/')
def index():
    """Render main page."""

@app.route('/login', methods = ['GET', 'POST'])
def login():
    if request.method == 'GET':
        """Load login page."""
    if request.method == 'POST':
        """Check for login request."""

@app.route('/signin', methods = ['GET', 'POST'])
def signin():
    if request.method == 'GET':
        """Load signin page."""
    if request.method == 'POST':
        """Check for signin request."""

@app.route('/topic/<topic_name>')
def topic(topic_name):
    sql.

@app.route('/user/<user_name>')
Example #10
0
# INVITE: https://discordapp.com/api/oauth2/authorize?client_id=566711902449827860&permissions=133692864&scope=bot

__version__ = '2.0.4'

parser = argparse.ArgumentParser(
	description="ShadowBot Discord Bot!")
parser.add_argument("--token", help="Discord Client Secret", type=str, metavar='', default=None)
parser.add_argument("--config", help="Config file path", type=str, metavar='', default=None)
args, unknown_args = parser.parse_known_args()

settings.set_file(args.config)
settings.load()
settings.register_setting("token", args.token)
settings.register_setting("database", settings.get_settings_base() + '/discord-db.sqldb')

sql.init(settings.get("database"))


def get_prefix(_bot, message):
	"""A callable Prefix for our bot. This could be edited to allow per server prefixes."""
	prefixes = ['>', '/']

	# If we are in a guild, we allow for the user to mention us or use any of the prefixes in our list.
	return commands.when_mentioned_or(*prefixes)(_bot, message)


# This is the directory all are located in.
cogs_base = 'cogs'
cogs_dir = abspath(dirname(__file__) + '/' + cogs_base)
sys.path.insert(0, cogs_dir)
bot = commands.Bot(command_prefix=get_prefix, description='ShadowBot v%s' % __version__, case_insensitive=True)
Example #11
0
import sql

app = flask.Flask(__name__)

ADMIN_TOKEN = os.environ.get("ADMIN_TOKEN")
if not ADMIN_TOKEN:
    logging.error('ADMIN_TOKEN must be set')
    sys.exit(1)

dbconn = sqlite3.connect('data/urls.db')
cursor = dbconn.cursor()
cursor.execute(
    "SELECT name FROM sqlite_master WHERE type='table' AND name='url_entries'")
if not cursor.fetchone():
    sql.init(dbconn)
dbconn.close()


@app.before_request
def prepare():
    """Connect to the database."""
    flask.g.dbconn = sqlite3.connect('data/urls.db')


@app.after_request
def finalize(response):
    """Close database connection."""
    flask.g.dbconn.close()
    return response