Пример #1
0
 async def send_on_member_join(self, member):
     welcome_type = database.get_data(guild=member.guild.id,
                                      data="welcome_type")
     greeting_type = database.get_data(guild=member.guild.id,
                                       data="greeting_type")
     if welcome_type != "none":
         welcome_msg = database.get_data(guild=member.guild.id,
                                         data="welcome_message")
         welcome_msg = welcome_msg.replace("{guild}", member.guild.name)
         welcome_msg = welcome_msg.replace("{member.mention}",
                                           member.mention)
         welcome_msg = welcome_msg.replace(
             "{member}", f"{member.name}#{member.discriminator}")
         if greeting_type == "image":
             img = await self.make_join_leave_image(
                 member.avatar_url_as(format="png", size=256),
                 "{0}#{1} has joined".format(
                     member.name, member.discriminator).capitalize(),
                 f"Welcome to {member.guild.name}",
             )
         if welcome_type == "channel":
             channel_id = database.get_data(guild=member.guild.id,
                                            data="welcome_channel")
             if channel_id is not None:
                 channel = self.client.get_channel(channel_id)
                 if greeting_type == "image":
                     return await channel.send(file=img)
                 return await channel.send(welcome_msg)
         if welcome_type == "dm":
             if greeting_type == "image":
                 return await member.send(file=img)
             return await member.send(welcome_msg)
 def __init__(self, db):
     self.article = self.get_article(db)
     self.training_questions = get_data(db, "question", "question",
                                        "WHERE is_train = 1")
     self.dev_questions = get_data(db, "question, article", "question",
                                   "WHERE is_train=0")
     self.vectorizer = self.train_vectorizer()
     self.article_vectors = self.get_article_vectors()
     self.dev_question_predictions = self.get_question_prediction()
Пример #3
0
 async def on_member_join(self, member):
     await self.send_on_member_join(member=member)
     autorole = database.get_data(guild=member.guild.id, data="autorole")
     if autorole:
         on_join_role = database.get_data(guild=member.guild.id,
                                          data="on_join_role")
         if on_join_role is not None:
             role = discord.utils.get(member.guild.roles, id=on_join_role)
             return await member.add_roles(role)
Пример #4
0
def home():
    if request.method == 'POST':
        name = request.form.get('name')
        msg = request.form.get('message')
        post(name,msg)
    database = get_data()
    return render_template("home.html",database=database)
Пример #5
0
 def get_model(self):
     training_data = get_data(self.N)
     X = training_data[self.x_columns]
     y = training_data[self.y_column]
     self.model = LinearRegression().fit(X, y)
     print(self.model.coef_)
     return self.model
Пример #6
0
    def update_records(self):

        #Delete entries from current display
        records = self.dbTree.get_children()

        for element in records:
            self.dbTree.delete(element)

        #Refill tree with updated data
        db_rows = db.get_data()
        self.dbTree.images = {}
        self.dbTree.imageNames = {}

        for row in db_rows:
            imgName = row[5]
            img = Image.open(imgName)
            img = img.resize((20, 20), Image.ANTIALIAS)
            img = ImageTk.PhotoImage(img)
            username = row[0]

            if (not username in self.selectList):
                self.dbTree.insert('',
                                   0,
                                   text=row[0],
                                   values=(row[1], row[2], row[3], row[4]),
                                   image=img)
                self.dbTree.images[row[0]] = img
                self.dbTree.imageNames[row[0]] = imgName
Пример #7
0
def execute_query(id):
    query = (q.query_list['get_query'], (id, ))
    result = db.get_data('sqlite', CONN, query)
    if result['status']:
        #query,num_of_rows,date_submitted,status,date_executed,application
        query = (result['data'][0][0], )
        num_of_rows = result['data'][0][1]
        status = result['data'][0][3]
        application = result['data'][0][5]
        database = result['data'][0][6]

        if status == 'SUBMITTED':
            conn_str = cn.get_connection(application, database)
            update_result = db.update_data(config.get_sql_type('database'),
                                           conn_str, query, num_of_rows)
            if update_result['status']:
                query = (
                    q.query_list['update_query'],
                    (datetime.now().strftime('%Y-%m-%d'),
                     update_result['data'], id),
                )
                querytable_update = db.update_data('sqlite', CONN, query, 1)
            return update_result
        else:
            {
                'data': None,
                'status': False,
                'message': "Query is not in SUBMITTED "
            }
Пример #8
0
def train_model(x_columns=['x'], y_column='y', N=1000):
    training_data = get_data(N)
    X = training_data[x_columns]
    y = training_data[y_column]
    model = LinearRegression().fit(X, y)
    print(model.coef_)
    return model
Пример #9
0
def index():

    try:
    	edu_programs_list = get_data('Москва')
    except:
    	edu_programs_list = [{'name':'Первая обучающая программа', 'description':'Описание программы 1. Много букв...', 'city':'Москва', 'link':'https://www.rambler.ru/'}, {'name':'Вторая обучающая программа', 'description':'Описание программы 2. Много букв...', 'city':'Тамбов', 'link':'https://www.yandex.ru/'}]
    
    return render_template('index.html', edu_programs_list=edu_programs_list, quantity_on_page=5+1)
Пример #10
0
def get_template_queries(user_id):
    query =(q.query_list['get_template_query'],(user_id,))
    result = db.get_data('sqlite',CONN,query)
    if result['status']:
        records = []
        for item in result['data']:
            records.append({"query_name": item[0],"query": item[1],"updated_columns": eval(item[2]),"where_columns": eval(item[3]),"application": item[4],"db": item[5]})
    return {"data":records,'status':result['status'], "message":result['message']}
Пример #11
0
def execute_query(incoming_query, query_name, app, db_name):
    query = (q.query_list['get_updated_row'],(query_name,))
    result = db.get_data('sqlite',CONN,query)
    if result['status']:
        conn_str = cn.get_connection(app,db_name)
        update_result = db.update_data(config.get_sql_type('database'),conn_str,(incoming_query,),result['data'][0]['expected_rows'])
        return update_result
    else:
        return {'data':None,'status':False,'message':'Invalid Query Name'}
Пример #12
0
def verify_query(query, application, database=None):
    list_of_queries = query.split(';')
    output = []
    for item in list_of_queries[:-1]:
        print(f"Processing the query {repr(item)}")
        query_match_group = query_pattern.match(item)
        print("The match group", query_match_group)
        column_group = query_match_group.group('columns')
        columns = []
        values = []
        for column_value in column_group.split(','):
            column_match_group = column_value_pattern.match(column_value)
            columns.append(column_match_group.group('column').strip())
            values.append(column_match_group.group('value').strip())

        print("Columns", columns)

        select_query = (
            f"select {','.join(columns)} from {query_match_group.group('table_name')} where {query_match_group.group('condition')}",
        )
        print("The select Query is", select_query)

        CONN = cn.get_connection(application, database)

        print("The connection string is", CONN)
        result = db.get_data(config.get_sql_type('database'), CONN,
                             select_query)

        if result['status']:
            number_of_records = len(result['data'])
            rows = []
            #print (result['data'].keys())
            for data in result['data']:
                print("The data processes is", data)
                d = {}
                row = 0
                for col in columns:
                    d[col] = data[row]
                    row += 1
                rows.append(d)
            output.append({
                'update_query': item,
                'select_query': select_query[0],
                'number_of_rows': number_of_records,
                'rows': rows,
                'status': 'Ok'
            })
        else:
            output.append({
                'update_query': item,
                'select_query': select_query[0],
                'number_of_rows': 'Error',
                'rows': 'Error',
                'status': str(result['message'])
            })
    print(output)
    return (output)
Пример #13
0
 def print_plan(self, message: telebot.types.Message, person_id):
     data = database.get_data(person_id, 'plan')
     if len(data) != 0:
         self.bot.send_message(message.from_user.id,
                               'Список дел на сегодня:\n' + '\n'.join(data))
     else:
         self.bot.send_message(
             message.chat.id,
             'Кажется, ты еще не составил свой список дел! Напиши слово'
             ' \'меню\', и сможешь его создать!')
Пример #14
0
def index():
    stock_list = database.get_data('stocks')
    if request.method == 'POST':
        selected_result = request.form.get('stock_list_form')
        return redirect(url_for('stock', stock=selected_result))
    return render_template(
        'index.html',
        stock_list=list(stock_list),
        update=database.update_db(get_days=True),
        days_counter=database.update_db(number_of_days=True))
Пример #15
0
def get_number_of_rows(query, application, db_name):
    print("Verify", application, db_name)
    CONN = cn.get_connection(application, db_name)
    result = db.get_data(config.get_sql_type('database'), CONN, query)
    status = True
    message = None
    number_of_records = 0
    if result['status']:
        number_of_records = len(result['data'])

    return {"data": number_of_records, "status": status, "message": message}
 def get_article(self, db):
     """
     generate article
     :param db: database connection
     :return: a dict with key: article id and value: list of paragraphs
     """
     paragraph = get_data(db, "context, article", "paragraph")
     article = defaultdict(list)
     for p in paragraph:
         article[p[1]].append(p[0])
     return article
Пример #17
0
 async def greeting_type(self, ctx, _type: str = None):
     if _type is not None:
         _type = _type.lower()
         if _type == "text" or _type == "image":
             async with ctx.channel.typing():
                 database.set_data(guild=ctx.guild.id,
                                   data="greeting_type",
                                   value=_type)
             return await ctx.send(f"Greeting has been set to `{_type}`.")
         return await ctx.send(
             "Greeting can only be set to either `text` or `image`")
     greeting = database.get_data(guild=ctx.guild.id, data="greeting_type")
     return await ctx.send(f"Greeting type is currenty set to `{greeting}`")
Пример #18
0
def analyze_volumes(period):
    """
    Wyszukuje skoków wolumenu u stosunku do średniej z danego okresu
        Parameters
    ----------
    period:List
        Lista z liczba dni, dla których wyliczamy średnią.
    """
    start_time = time.time()
    stocks_list = database.get_data('stocks')
    df = pd.DataFrame(stocks_list, columns=['TICKER', 'NAME', 'ISIN'])
    df_results = pd.DataFrame(
        columns=['NAME', 'PERIOD', 'CHANGE', 'CLOSE', 'DAILY'])
    for name in df['NAME']:
        try:
            data = get_stock_data(name)
            current_volume = data.iloc[-1]['VOLUME']
            vol_value = float(data.iloc[-1]['CLOSE']) * current_volume
            if vol_value > 80000:
                for value in period:
                    mean = stock_mean_volume(data[-value:]['VOLUME'])
                    current_volume = data[-value:].iloc[-1]['VOLUME']
                    vol_percent = round((((current_volume / mean) - 1) * 100),
                                        2)
                    close_price = list(database.check_last_entries(name,
                                                                   1))[0][5]
                    t_min = data.tail().iloc[-2]['CLOSE']
                    t = data.tail().iloc[-1]['CLOSE']
                    d_return = round(((t / t_min) - 1) * 100, 2)
                    df_results = df_results.append(
                        {
                            'NAME': name,
                            'PERIOD': value,
                            'CHANGE': vol_percent,
                            'CLOSE': float(close_price),
                            'DAILY': float(d_return)
                        },
                        ignore_index=True)
                    print(name, value)
            else:
                print("Za mały obrót", name)
        except Exception as e:
            print(name, " Error", e)
    result_table = []
    for p_value in period:
        r_item = df_results[df_results['PERIOD'].isin([p_value])].sort_values(
            by=['CHANGE'], ascending=False)
        result_table.append(r_item.values.tolist())
    print("Executed in : {} seconds".format(time.time() - start_time))

    return result_table
Пример #19
0
def smacrossing():
    results = []
    sma_15_results = []
    stock_list = database.get_data('stocks')
    for stock in stock_list:
        values = analytics.sma_crossing(stock[1], 50, 200)
        results.append(values)
        sma_15 = analytics.sma_price_crossing(stock[1], 15)
        sma_15_results.append(sma_15)
    results = list(filter(None, results))
    sma_15_results = list(filter(None, sma_15_results))
    return render_template('sma.html',
                           sma_crossing=results,
                           sma_15=sma_15_results)
Пример #20
0
 async def welcome_type(self, ctx, type_: str = None):
     if type_ is not None:
         type_ = type_.lower()
         if type_ == "channel" or type_ == "dm" or type_ == "none":
             async with ctx.channel.typing():
                 database.set_data(guild=ctx.guild.id,
                                   data="welcome_type",
                                   value=type_)
             return await ctx.send(f"Welcome type is set to `{type_}`")
         return await ctx.send(
             "The available welcome types are `channel`, `dm`, `None`")
     async with ctx.channel.typing():
         type_ = database.get_data(guild=ctx.guild.id, data="welcome_type")
     await ctx.send(f"Current welcome type is `{type_}`")
Пример #21
0
 async def system_channel(self, ctx, channel: discord.TextChannel = None):
     if channel is not None:
         async with ctx.channel.typing():
             database.set_data(guild=ctx.guild.id,
                               data="bot_msg_channel",
                               value=channel.id)
         return await ctx.send(
             f"The bot message channel is set to {channel.mention}")
     async with ctx.channel.typing():
         bot_channel_id = database.get_data(guild=ctx.guild.id,
                                            data="bot_msg_channel")
         bot_channel = self.client.get_channel(bot_channel_id)
     await ctx.send(
         f"Current bot message channel is set to {bot_channel.mention}")
Пример #22
0
 async def welcome_channel(self, ctx, channel: discord.TextChannel = None):
     if channel is not None:
         async with ctx.channel.typing():
             database.set_data(guild=ctx.guild.id,
                               data="welcome_channel",
                               value=channel.id)
         return await ctx.send(
             f"Welcome channel is set to {channel.mention}")
     async with ctx.channel.typing():
         welcome_channel_id = database.get_data(guild=ctx.guild.id,
                                                data="welcome_channel")
         welcome_channel = self.client.get_channel(welcome_channel_id)
     await ctx.send(
         f"Current welcome channel is set to {welcome_channel.mention}")
Пример #23
0
    def print_timetable(self, message: telebot.types.Message, person_id):
        data = database.get_data(person_id, 'timetable')
        now_date = datetime.datetime.now()
        now_weekday = calendar.day_name[now_date.weekday()]
        if now_weekday.lower() != 'sunday':
            self.bot.send_message(message.chat.id, 'Расписание на сегодня:')
        else:
            self.bot.send_message(message.chat.id, 'Сегодня нет занятий!')

        for elem in data:
            if elem[0] == now_weekday:
                self.bot.send_message(
                    message.chat.id,
                    'Предмет: ' + elem[1] + ', время: ' + elem[2] + ';')
Пример #24
0
    def gera_jogo_mega_sena(self, size=6):

        jogo = self.gera_numeros_mega_sena(size)
        resposta = 'Jogo válido'
        for x in database.get_data():
            lista = x[1].replace("[", "")
            lista = lista.replace("]", "")
            lista = lista.split(",")
            match = 0
            for y in range(6):
                if int(lista[y]) in jogo:
                    match += 1
            if match == 6:
                resposta = 'Jogo inválido!'
                break
        print(resposta, jogo)
Пример #25
0
 async def on_join_role(self, ctx, role: discord.Role = None):
     if role is not None:
         async with ctx.channel.typing():
             database.set_data(guild=ctx.guild.id,
                               data="on_join_role",
                               value=role.id)
         return await ctx.send(
             f"On join role has been sent to {role.mention}")
     async with ctx.channel.typing():
         role_id = database.get_data(guild=ctx.guild.id,
                                     data="on_join_role")
         role = discord.utils.get(ctx.guild.roles, id=role_id)
     if role is not None:
         return await ctx.send(
             f"Currently on join role is set to {role.mention}")
     await ctx.send("-settings onjoinrole <role>")
Пример #26
0
    async def welcome_msg(self, ctx, *, msg: str = None):
        if msg is not None:
            async with ctx.channel.typing():
                database.set_data(guild=ctx.guild.id,
                                  data="welcome_message",
                                  value=msg)
            return await ctx.send(f"Welcome message is set to {msg}")
        async with ctx.channel.typing():
            welcome_msg = database.get_data(guild=ctx.guild.id,
                                            data="welcome_message")
        await ctx.send(f"Current welcome message is ```\n" + welcome_msg +
                       """\n```\n
While setting welcome message you can use variables like;
`{guild}` (will be replaced with the Server name.)
`{member.name}` (will be replaced with the name of the new member.)
`{member.mention}` (will ping the member.)
""")
Пример #27
0
def get_queries(userid):
    query = (q.query_list['get_queries'], (userid, ))
    result = db.get_data('sqlite', CONN, query)
    records = []
    for item in result['data']:
        #query,num_of_rows,date_submitted,status,date_executed,application
        records.append({
            "query": item[0],
            "num_of_rows": item[1],
            "date_submitted": item[2],
            "status": item[3],
            "date_executed": item[4],
            "application": item[5]
        })
    return {
        'data': records,
        'status': result['status'],
        'message': result['message']
    }
Пример #28
0
def volatility_scan():
    stock_list = database.get_data('stocks')
    results = []
    for stock in stock_list:
        # if stock[1] =='ARAMUS':
        #         break;
        try:
            stock_data = analytics.get_stock_data(stock[1])
            turnover = stock_data.iloc[-1]['VOLUME'] * float(
                stock_data.iloc[-1]['CLOSE'])
            if turnover > 30000:
                stock_volatility_state = analytics.volatility(stock_data)
                if stock_volatility_state.index[
                        0] and stock_volatility_state[:1][1] >= 5:
                    results.append([stock[1], stock_volatility_state[:1][1]])
                    print(stock[1], stock_volatility_state[:1][1])
                else:
                    print(stock[1], "no match")
        except Exception as e:
            print(stock[1], e)
    return render_template('volatility.html', results_display=results)
Пример #29
0
def get_query_in_queue(executor_user):
    query = (q.query_list['query_queue'],(executor_user,))
    result = db.get_data('sqlite',CONN,query)
    print (result)
    records = []
    if result['status']:
        #a.id, a.query, a.num_of_row,a.application,a.user_id
        for item in result['data']:
            print ("Processing Record", item)
            select_query = item[2]
            db_name = item[5]
            app_name = item[4]
            result = ver.get_number_of_rows(select_query,app_name,db_name)
            if result['status']:
                current_rows =  result['data']
            #current_rows =  0

            #a.id, a.query, a.select_query,a.num_of_rows,a.application,a.database,a.user_id
            records.append({"id":item[0],"update_query":item[1],"num_of_rows": item[3],"current_rows":current_rows,"application": item[4], "user": item[6]})
        
    return {"data":records,"status":result['status'],"message":result['message']}
Пример #30
0
 async def autorole(self, ctx, option: str = None):
     if option is not None:
         option = option.lower()
         if option == "true":
             async with ctx.channel.typing():
                 database.set_data(guild=ctx.guild.id,
                                   data="autorole",
                                   value=True)
             return await ctx.send(
                 "Autorole has been set to `True`. Use `-settings onjoinrole <role>` to set the role."
             )
         if option == "false":
             async with ctx.channel.typing():
                 database.set_data(guild=ctx.guild.id,
                                   data="autorole",
                                   value=False)
             return await ctx.send("Autorole has been set to `False`.")
         return await ctx.send(
             "Autorole can only be set to either `True` or `False`")
     async with ctx.channel.typing():
         autorole = database.get_data(guild=ctx.guild.id, data="autorole")
     await ctx.send(f"Currently autorole is set to `{autorole}`")