def home():

    content = {'question':'','confidence':'','response_title':'','response_content':''}
    data = functions.getData()
    content['infected_count'] = data['infected']
    content['recovered_count'] = data['recovered']
    content['death_count'] = data['deaths']
    content['death_rate'] = data['death_rate']
    content['recovery_rate'] = data['recovery_rate']
    content['datetime'] = data['datetime']


    if request.method == 'POST':
        question = request.form['question']  #get question from form

        print(question)
        content['question'] = question
        question = functions.check(question)
        print('corrected question: ' + question)
        qtn = vectorizer.transform([question])  #transform to a vector
        qtn = qtn.toarray()  #transform to array
        prediction = virtual_agent_model.predict(qtn)
        print(responses.class_names[np.argmax(prediction[0])])
        content['response_title'] = responses.class_names[prediction[0]]
        content['response_content'] = responses.class_responses[prediction[0]]

    return render_template('index.html', content=content)
Exemple #2
0
def cmd(api, message, args):
    for_all = None if message['from_id'] == message['peer_id'] else True

    banned = functions.getData('banned_peers')
    if banned is None: banned = []

    if message['peer_id'] in banned:
        api.messages.edit(
            peer_id=message['peer_id'],
            message_id=message['id'],
            message=
            f"{config.prefixes['invalid']} Данная беседа уже заблокирована.")
        time.sleep(3)
        api.messages.delete(message_ids=message['id'], delete_for_all=for_all)

    banned.append(message['peer_id'])
    edit = functions.editData('banned_peers', banned)

    if edit:
        api.messages.edit(
            peer_id=message['peer_id'],
            message_id=message['id'],
            message=
            f"{config.prefixes['success']} Данная беседа была заблокирована!")
    else:
        api.messages.edit(
            peer_id=message['peer_id'],
            message_id=message['id'],
            message=
            f"{config.prefixes['error']} Данную беседу не получилось заблокировать. Возможно данные повреждены."
        )

    return
Exemple #3
0
def cmd(api, message):
    banned = functions.getData('banned_peers')
    if banned is None: banned = []

    if not (message['peer_id'] in banned):
        api.messages.edit(
            peer_id=message['peer_id'],
            message_id=message['id'],
            message=
            f"{config.prefixes['invalid']} Данная беседа не заблокирована.")
        return

    banned.remove(message['peer_id'])
    edit = functions.editData('banned_peers', banned)

    if edit:
        api.messages.edit(
            peer_id=message['peer_id'],
            message_id=message['id'],
            message=
            f"{config.prefixes['success']} Данная беседа была разблокирована!")
    else:
        api.messages.edit(
            peer_id=message['peer_id'],
            message_id=message['id'],
            message=
            f"{config.prefixes['error']} Данную беседу не получилось разблокировать. Возможно данные повреждены."
        )

    return
Exemple #4
0
def cmd(api, message, args, owner_id):
    for_all = None if message['from_id'] == message['peer_id'] else True

    if message.get('reply_message') is not None:
        target = api.users.get(user_ids=message['reply_message']['from_id'])
    else:
        try:
            target = api.users.get(user_ids=functions.getUserId(args[1]))
        except:
            api.messages.edit(
                peer_id=message['peer_id'],
                message_id=message['id'],
                message=
                f"{config.prefixes['error']} Необходимо ответить на сообщение пользователя или указать на него ссылку: /ignore [пользователь]"
            )
            time.sleep(3)
            api.messages.delete(message_ids=message['id'],
                                delete_for_all=for_all)
            return

    ignored_users = functions.getData('ignore')
    if ignored_users is None: ignored_users = []

    target = target[0]
    if target['id'] in ignored_users:
        api.messages.edit(
            peer_id=message['peer_id'],
            message_id=message['id'],
            message=
            f"{config.prefixes['invalid']} [id{target['id']}|{target['first_name']} {target['last_name']}] уже игнорируется."
        )
        return

    if owner_id == target['id']:
        api.messages.edit(peer_id=message['peer_id'],
                          message_id=message['id'],
                          message="❌ Нельзя игнорировать самого себя!")
        return

    ignored_users.append(target['id'])
    edit = functions.editData('ignore', ignored_users)

    if edit:
        api.messages.edit(
            peer_id=message['peer_id'],
            message_id=message['id'],
            message=
            f"{config.prefixes['success']} [id{target['id']}|{target['first_name']} {target['last_name']}] теперь будет игнорироваться!"
        )
    else:
        api.messages.edit(
            peer_id=message['peer_id'],
            message_id=message['id'],
            message=
            f"Пользователя {config.prefixes['error']} [id{target['id']}|{target['first_name']} {target['last_name']}] не получилось отправить в игнор. Возможно данные повреждены."
        )

    return
Exemple #5
0
def getmethod():
    link = functions.getLinks()
    data = functions.getData(link)
    res = json.dumps(data)

    #constants.zzz
    #aaa = requests.get(constants.monthrepayapi+'1000000', headers = constants.header, proxies = constants.proxies)
    # bbb = str(aaa)
    # print(bbb)
    # linkk = str(link)
    return res
Exemple #6
0
def cmd(api, message, args):
    for_all = None if message['from_id'] == message['peer_id'] else True

    if message.get('reply_message') is not None:
        target = api.users.get(user_ids=message['reply_message']['from_id'])
    else:
        try:
            target = api.users.get(user_ids=functions.getUserId(args[1]))
        except:
            api.messages.edit(
                peer_id=message['peer_id'],
                message_id=message['id'],
                message=
                f"{config.prefixes['error']} Необходимо ответить на сообщение пользователя или указать на него ссылку: /unban [пользователь]"
            )
            time.sleep(3)
            api.messages.delete(message_ids=message['id'],
                                delete_for_all=for_all)
            return

    banned = functions.getData('banned')
    if banned is None: banned = []

    target = target[0]
    if not (target['id'] in banned):
        api.messages.edit(
            peer_id=message['peer_id'],
            message_id=message['id'],
            message=
            f"{config.prefixes['invalid']} [id{target['id']}|{target['first_name']} {target['last_name']}] не заблокирован."
        )
        return

    banned.remove(target['id'])
    edit = functions.editData('banned', banned)

    if edit:
        api.messages.edit(
            peer_id=message['peer_id'],
            message_id=message['id'],
            message=
            f"{config.prefixes['success']} [id{target['id']}|{target['first_name']} {target['last_name']}] был разблокирован!"
        )
    else:
        api.messages.edit(
            peer_id=message['peer_id'],
            message_id=message['id'],
            message=
            f"{config.prefixes['error']} Пользователя [id{target['id']}|{target['first_name']} {target['last_name']}] не получилось разблокировать. Возможно данные повреждены."
        )

    return
Exemple #7
0
def cmd(api, message, args):
    for_all = None if message['from_id'] == message['peer_id'] else True

    if message.get('reply_message') is not None:
        target = api.users.get(user_ids=message['reply_message']['from_id'])
    else:
        try:
            target = api.users.get(user_ids=functions.getUserId(args[1]))
        except:
            api.messages.edit(
                peer_id=message['peer_id'],
                message_id=message['id'],
                message=
                f"{config.prefixes['error']} Необходимо ответить на сообщение пользователя или указать на него ссылку: /unignore [пользователь]"
            )
            time.sleep(3)
            api.messages.delete(message_ids=message['id'],
                                delete_for_all=for_all)
            return

    ignored_users = functions.getData('ignore')
    if ignored_users is None: ignored_users = []

    target = target[0]
    if not (target['id'] in ignored_users):
        api.messages.edit(
            peer_id=message['peer_id'],
            message_id=message['id'],
            message=
            f"{config.prefixes['invalid']} [id{target['id']}|{target['first_name']} {target['last_name']}] не игнорируется."
        )
        return

    ignored_users.remove(target['id'])
    edit = functions.editData('ignore', ignored_users)

    if edit:
        api.messages.edit(
            peer_id=message['peer_id'],
            message_id=message['id'],
            message=
            f"{config.prefixes['success']} [id{target['id']}|{target['first_name']} {target['last_name']}] был удалён из списка игнорируемых!"
        )
    else:
        api.messages.edit(
            peer_id=message['peer_id'],
            message_id=message['id'],
            message=
            f"Пользователя {config.prefixes['error']} [id{target['id']}|{target['first_name']} {target['last_name']}] не получилось удалить из списка игнорируемых. Возможно данные повреждены."
        )

    return
Exemple #8
0
def new_user(request):
    alert = "fail"
    if request.method == 'POST':
        name = request.POST['name']
        email = request.POST['email']
        password = request.POST['password']
        if not getData("Marks", "Students", {"email": email}):
            insertRecord("Marks", "Users", {
                "name": name,
                "email": email,
                "password": password
            })
            alert = "success"
    return JsonResponse(alert, safe=False)
Exemple #9
0
def month(month_id):
    for month in months:
        if (month[1] == month_id):
            url = month[2]
            break;
    kinotekaFile = getKinotekaFile(url)

    table = getData(url, kinotekaFile)
    headings = table[0]
    data = []
    for row in table[1:]:
        data.append(row)

    return render_template("table.html", headings=table[0], data=data,
                                         months=months, monthName=month[0])
Exemple #10
0
                        'graffiti': '• граффити'
                    }  # TODO: доработать (добавить ссылки на содержимое)

                    for replace in replacer:
                        text = text.replace(replace, replacer[replace])
                else:
                    text = "• пересланные сообщения"

            if message['peer_id'] > 2000000000:
                print(f"\033[34m[{current_time}] "
                      f"\033[37m[\033[32m{getChatName(message['peer_id'])}\033[37m/\033[31m{getUserName(message['from_id'])}\033[37m]: \033[36m{text}")
            else:
                print(f"\033[34m[{current_time}] "
                      f"\033[37m[ЛС] [\033[32m{getUserName(message['peer_id'])}\033[37m/\033[31m{getUserName(message['from_id'])}\033[37m]: \033[36m{text}")

        ignored_users = functions.getData('ignore')
        if ignored_users is not None:
            if message['from_id'] in ignored_users:
                api.messages.delete(
                    message_ids=message['id'],
                    delete_for_all=0
                )
                continue

        banned = functions.getData('banned')
        if banned is not None:
            if message['from_id'] in banned:
                continue

        banned_peers = functions.getData('banned_peers')
        if banned_peers is not None:
Exemple #11
0
def placeOrders():
    ordersPlaced = request.json
    orderList = functions.getData()['orders']
    productList = functions.getData()['products']
    pendingOrders = []
    unfulfillableOrders = []
    fulfilledOrders = []
    stockToReorder = []
    response = {}

    #Finds the JSON data associated with orderIds from array input
    for order in orderList:
        if order['orderId'] in ordersPlaced['orderIds']:
            pendingOrders.append(order)

    #Loops through all requested orders and determines if they can be filled
    #assumes orders can be filled until proven otherwise
    for order in pendingOrders:
        if order["items"] is not None and len(order["items"]) > 0:
            productsInStock = True
            for desiredItem in order['items']:
                stockItem = functions.getProduct(desiredItem['productId'],
                                                 productList)

                if (desiredItem['quantity'] > stockItem['quantityOnHand']):
                    productsInStock = False
                    if order not in unfulfillableOrders:
                        order['status'] = "Error: Unfulfillable"
                        unfulfillableOrders.append(order)

            #if the order was not flagged as unfulfillable then it is filled
            #if stock is taken below threshhold it is noted
            if productsInStock and order['status'] == 'Pending':
                for desiredItem in order['items']:
                    stockItem = functions.getProduct(desiredItem['productId'],
                                                     productList)
                    stockItem['quantityOnHand'] -= desiredItem['quantity']
                    if (stockItem['quantityOnHand'] <
                            stockItem['reorderThreshold']):
                        if stockItem not in stockToReorder:
                            stockToReorder.append(stockItem)
                order['status'] = 'Fulfilled'
                fulfilledOrders.append(order)

    #Stock is reordered once all fulfillable reorders are placed
    #This is done after to prevent duplicate reorders
    functions.reorderStock(stockToReorder)

    print("Orders Placed:")
    print(ordersPlaced['orderIds'])
    print("------------------------")
    print('Orders Fulfilled:')
    for order in fulfilledOrders:
        print(order['orderId'])
    print("------------------------")
    print('Orders Unfulfilled:')
    for order in unfulfillableOrders:
        print(order['orderId'])
        if "unfillable" in response:
            response["unfillable"].append(order['orderId'])
        else:
            response["unfillable"] = [order['orderId']]
    print("------------------------")

    #print (orderList)
    #print(ordersPlaced)
    return jsonify(response)
Exemple #12
0
def postmethod():
    link = functions.getLinks()
    data = functions.getData(link)
    res = json.dumps(data)
    return res
               transcript_SET_G = transcript_SET
               sameSeqTupleList= list()
               for t in transcript_SET:
                    mutantLowestScoreTuple = functions.getLowestScore(mutant_Map[t][0], IEDBTuples )
                    IEDB_transcriptMap_MT[t].append( dataTuple( mer = num, data = mutantLowestScoreTuple))
                    IEDB_transcriptMap_WT[t].append(dataTuple( mer= num, data = functions.getLowestScore(wildType_Map[t][0], IEDBTuples )))
                    IEDB_TranscriptMap_SameSeq[t].append(dataTuple( mer= num, data = functions.getSameSeqScore(mutantLowestScoreTuple, wildType_Map[t][0], IEDBTuples )))
                    peptideSet.update(functions.getPeptides(IEDB_transcriptMap_MT[t],num))
                    peptideSet.update(functions.getPeptides(IEDB_transcriptMap_WT[t],num) )
                    peptideSet.update(functions.getPeptides(IEDB_TranscriptMap_SameSeq[t],num) )

          for transcript in transcript_SET_G:
               fwrite.write(patient+  tab + hla+ tab + transcript )
               merList  = list()
               for num in isomers:
                    position, peptide, bindingScore = functions.getData(IEDB_transcriptMap_MT[transcript], num)
                    merList.append((num,float(bindingScore), peptide))
                    if num == "15":
                         fwrite.write(tab  + "MT")
                    fwrite.write(tab + str(position) + tab + str(peptide) + tab + str(bindingScore))
               fileData = functions.getFinalMer(merList)
               mer = fileData[0]
               score = fileData[1]
               peptide = fileData[2]
               fwrite.write(tab+ peptide + tab + mer + tab+ str(score))

               merList  = list()
               for num in isomers:
                    position, peptide, bindingScore = functions.getData(IEDB_transcriptMap_WT[transcript], num)
                    merList.append((num,float(bindingScore),peptide))
                    if num == "15":
Exemple #14
0
import functions
from pprint import pprint 

fileName = raw_input("Enter informative file name: ")
option = raw_input("Enter searching option (key / value): ")

data = functions.getData(fileName)
if data == None:
    print "Get data failed"
    exit()

# Function returns search result
# param - Nope
# return - mixed: None, int or string
def search():
    if option == 'key':
        key = raw_input("Enter key to search: ")
        value = functions.findByKey(key, **data)
        return value
    elif option == 'value':
        try:
            value = int (raw_input("Enter value to search: "))
        except ValueError:
            print "Inavlid value"
            return None
        keys = functions.findByValue(value, **data)
        return keys
    else:
        print "Unknown option"
        return None
Exemple #15
0
r = getPlayers()
# just want the names
rostered = []
for p in r:
    rostered.append(p[0].lower())

# free agents

free_agents = []
with open('data/player_values.json', 'r') as file:
    player_values = json.loads(file.read())
for player in player_values.keys():
    if player not in rostered:
        free_agents.append([player, player_values[player]])

# print free agents in descending order of value, with value greater than the min
free_agents.sort(key=lambda e: -e[1])
print('Free agents:')
for p, v in free_agents:
    if v >= MIN_VALUE:
        print(f"{p} -- {v}")

# print your team
data = getData()
info = getInfo()
t = data[info['me']]
t.sort(key=lambda e: e[2])
print('\nMy team:')
for p, _, v in t:
    print(f"{p} -- {v}")
Exemple #16
0
import functions as f
import itertools
import numpy as np
import plotly.plotly as py
import plotly.graph_objs as go
import random

name = "Peter"
filepath = "C:/Users/Peter/Dropbox/Programming/Python/track-analysis/" + name + "/" + name + ".txt"
count, data = f.getData(filepath)
start, end = f.getDateRange(data)

'''
0. Click Type (pie)
1. Monitor Use (pie)
2. Clicks Per Date (line)
3. Hours Per Session (line)
4. Frequency Of Turn On Times (histogram)
5. Frequency Of Shutdown Times (histogram)
6. Click Mapping (scatter)
7. Frequency Of Seconds Between Clicks (histogram)
8. Clicks By The Hour (bar)
9. Clicks By The Day (bar)
10. Frequency Of Clicks Per Session (histogram)
11. Frequency Of Hours Per Session (histogram)
'''

'''
fig0 = {
    'data': [{
		'labels': ['Left', 'Right', 'Middle', '1', '2'],
Exemple #17
0
import pandas as pd
import backtest as twp

from functions import getData
import numpy as np
# get price & techinical indicator data as pandas dataframe
data, data_prev, sma20, sma80, slowD, slowK = getData()
signal = pd.Series(index=np.arange(len(data)))

for i in range(signal.shape[0]):
    signal.loc[i] = 10
#signal.loc[1] = 0
signal.loc[0] = 1
print(signal)
bt = twp.Backtest(pd.Series(data=[x for x in data], index=signal.index.values),
                  signal,
                  signalType='shares')
endReward = bt.pnl.iloc[-1]
print(bt.data)
print(signal.shape[0])
print(endReward)
#stoch = stoch.tail(1000)
print(stoch.iloc[0],'\n',stoch.iloc[-1],'\n')
#print(stoch.to_string())

rsi = rsi[879:1178]
#rsi = rsi.tail(1000)
print(rsi.iloc[0],'\n',rsi.iloc[-1],'\n')

dji = dji.reset_index()
dji = dji['4. close']
#price = np.expand_dims(price,axis=1)
dji = np.expand_dims(dji,axis=1)
scaler = preprocessing.StandardScaler() #unit standard derivation and 0 mean
dji = scaler.fit_transform(dji)
#price = scaler.fit_transform(price)
'''

#   '''
# get price & techinical indicator data as pandas dataframe
pdata, data = getData(-1)

print(data)
plt.plot(data, 'r')
#plt.plot(sma20,'g')
#plt.plot(sma80,'b')
#plt.plot(dji)
plt.savefig('csv/stock.png')
plt.show()

#'''