예제 #1
0
 def buscar(self):
     print("---------------------")
     print("Buscador de contactos")
     print("---------------------")
     nombre = input("Introduzca el nombre del contacto: ")
     get_data(nombre)
     '''for x in range(len(self.contactos)):
예제 #2
0
파일: main.py 프로젝트: jendyren/emission
def profile():
    username = flask_login.current_user.id

    userid = request.cookies.get('userID')
    scores = db.get_data(userid, ['scores'])['scores']

    score = db.get_data(userid, ['score'])['score']
    friends = db.get_data(userid, ['friends'])
    friends = [] if 'friends' not in friends else friends["friends"]

    return render_template('profile.html',
                           username=username,
                           friends=friends,
                           score=score)
예제 #3
0
 def editar(self):
     print("---------------")
     print("Editar contacto")
     print("---------------")
     nom_buscado = input("Introduzca el nombre del contacto: ")
     get_data(nom_buscado)
     print(
         'A continuacion solicitaremos que ingrese los datos para actualizarlos'
     )
     nombre = input("Introduzca el nuevo nombre: ")
     apellido = input("Introduzca el nuevo apellido: ")
     telefono = input("Introduzca el nuevo teléfono: ")
     email = input("Introduzca el nuevo email: ")
     update_data(nom_buscado, nombre, apellido, telefono, email)
     '''condition = False
예제 #4
0
    def predict(self):
        """Построение предсказаний"""
        """
        1. Сбор данных по reg_nums
        2. Предобработка данных
        3. Построение предсказания
        """

        # Извлечение данных из БД
        data = get_data(self.reg_nums)

        # TODO: убрать заглушка по построению предсказания
        response = []
        for reg_num in data.cntr_reg_num.values:
            # Случайные предсказания
            pred_class = random.randint(0, 1)
            pred_proba = random.uniform(
                0, 0.49) if not pred_class else random.uniform(0.5, 1)
            response.append({
                'reg_num': reg_num,
                'pred_class': pred_class,
                'pred_proba': round(pred_proba, 2)
            })

        return response
예제 #5
0
파일: table.py 프로젝트: Layts/pyqt
 def __init__(self):
     super().__init__()
     self.table = QtWidgets.QTableView()
     self.setWindowTitle('Тестовое задание')
     self.resize(1000, 500)
     self.model = TableModel(db.get_data())
     self.table.setModel(self.model)
     self.setCentralWidget(self.table)
예제 #6
0
def stored_inferences():
    if request.method == 'POST':
        if not request.is_json:
            return jsonify({"msg": "Missing JSON in request"}), 400

        add_data(request.get_json())
        return 'Inference Added'

    return render_template("stored_inferences.html", data=get_data())
예제 #7
0
파일: main.py 프로젝트: jendyren/emission
def dashboard():
    username = flask_login.current_user.id
    print('Logged in as: ' + username)
    userid = request.cookies.get('userID')
    #print(db.get_data(userid, []))
    scores = db.get_data(userid, ['score'])["score"]

    activities = db.get_data(userid, ['activities'])
    if request.method == 'POST' and request.form:
        activities = {}
        date = "d" + request.form["date"].replace("/", '_')
        for i, val in request.form.items():
            if i == 'date': continue
            if val.lstrip('-+').isdigit(): val = int(val)
            activities['activities.' + i.replace('-', '.') + '.' + date] = val
        db.updateActivities(userid, activities)
        flash("Your responses have been saved!")
    return render_template('index.html', username=username)
예제 #8
0
def reply():
    num = request.form.get("From")
    num = num.replace("whatsapp:", "")
    msg_text = request.form.get("Body")
    #x=collection.find_one({"NUMBER":num})

    data = get_data(msg_text)
    msg = MessagingResponse()
    resp = msg.message(data)
    return (str(msg))
예제 #9
0
파일: main.py 프로젝트: PiPiNaN/goodstudy
def gethanzi(id=0):
    r = db.get_data(db.sql_connection(), (id, ))
    a = {}
    for i in r:
        a["id"] = i[0]
        a["hanzi"] = i[1]
        a["type"] = i[2]
        a["learned"] = i[3]
        a["passed"] = i[4]
    return jsonify(a)
예제 #10
0
def get_keyterms():
    print("getting terms")
    result = db.get_data('''SELECT term FROM keyterms''')

    terms = []
    for row in result:
        print('{0}'.format(row[0]))
        term = row[0]
        terms.append(term)
    return terms
예제 #11
0
def get_articles():
    result = db.get_data(
        '''SELECT id, title, content, strftime('%Y-%m-%d %H:%M', createddate), \
                            published, image, thumb, url FROM articles''')

    articles = []
    for row in result:
        terms = db.get_data(
            '''SELECT term FROM keyterms as kt INNER JOIN articleterms \
                        as at ON kt.id = at.termid WHERE at.articleid = ''' +
            str(row[0]))

        print('{0}'.format(terms[0]))
        article = Article(row[0], row[1], row[2], row[3], row[4], row[5],
                          row[6], row[7], terms)

        articles.append(article)

    return articles
예제 #12
0
def judge_limit(id, question_id, data_num, time_limit, mem_limit, language,
                dblock):
    # low_level()
    """评测一组数据"""
    # 从数据库获取数据
    input_path = os.path.join(config.work_dir, str(question_id),
                              'data%s.in' % data_num)
    try:
        input_data = open(input_path, "a")
        data_list = get_data(question_id)
    except:
        return False

    output_path = os.path.join(config.work_dir, str(id),
                               'out%s.txt' % data_num)
    temp_out_data = open(output_path, 'w')
    if language == 'java':
        cmd = 'java -cp %s Main' % (os.path.join(config.work_dir, str(id)))
        main_exe = shlex.split(cmd)
    elif language == 'python2':
        cmd = 'python2 %s' % (os.path.join(config.work_dir, str(id),
                                           'main.pyc'))
        main_exe = shlex.split(cmd)
    elif language == 'python3':
        cmd = 'python3 %s' % (os.path.join(config.work_dir, str(id),
                                           '__pycache__/main.cpython-33.pyc'))
        main_exe = shlex.split(cmd)
    elif language == 'lua':
        cmd = "lua %s" % (os.path.join(config.work_dir, str(id), "main"))
        main_exe = shlex.split(cmd)
    elif language == "ruby":
        cmd = "ruby %s" % (os.path.join(config.work_dir, str(id), "main.rb"))
        main_exe = shlex.split(cmd)
    elif language == "perl":
        cmd = "perl %s" % (os.path.join(config.work_dir, str(id), "main.pl"))
        main_exe = shlex.split(cmd)
    else:
        main_exe = [
            os.path.join(config.work_dir, str(id), 'main'),
        ]
    runcfg = {
        'args': main_exe,
        'fd_in': input_data.fileno(),
        'fd_out': temp_out_data.fileno(),
        'timelimit': time_limit,  # in MS
        'memorylimit': mem_limit,  # in KB
    }
    low_level()
    rst = lorun.run(runcfg)
    input_data.close()
    temp_out_data.close()
    logging.debug(rst)
    return rst
예제 #13
0
def write_on_redis(querysql, type):
    try:
        redisConnection = redis.ConnectionPool(
            host=config.get('redis', 'redis_ip'),
            port=int(config.get('redis', 'redis_port')),
            db=int(config.get('redis', 'redis_db')))
        redisContext = redis.Redis(connection_pool=redisConnection)

        minHotMark = rank_algorithm.standard_mark()
        print("最小的值为:" + str(minHotMark))

        dataset = db.get_data(querysql, type)

        for k, v in dataset.items():
            hotPost = []

            if len(v) > 10:
                score = {}

                for post in v:
                    # print(rank_algorithm.hot(post[13], post[3], post[9], post[7]))
                    scoreNum = rank_algorithm.hot(post[13], post[3], post[9],
                                                  post[7])
                    if scoreNum >= minHotMark:
                        if scoreNum not in score:
                            score[scoreNum] = []
                            score[scoreNum].append(post)
                        else:
                            score[scoreNum].append(post)
                d = []
                for key in score.keys():
                    d.append(key)

                count = 0
                sortdata = quick_max_k.qselect(d, MAX_K)
                for sortk in sortdata[::-1]:
                    for p in score[sortk][::-1]:
                        if (count >= 10):
                            break

                        hotPost.append(convert_to_json(p))

                        count = count + 1
                print(k + '_hot_post' +
                      json.dumps(hotPost, separators=(',', ':')))

                redisContext.set(k + '_hot_post',
                                 json.dumps(hotPost, separators=(',', ':')))

    except redis.ConnectionError as err:
        print("connect redis' failed.")
        print("Error: {}".format(err.msg))
예제 #14
0
def login():
    if request.method == 'GET':
        return render_template("login.html")
    else:
        email = request.form['email']
        pwd = request.form['pwd']
        print("전달된값:", email, pwd)
        ret = db.get_data(email, pwd)
        if ret != 'None':
            session['email'] = email
            return "로그인 성공"
        else:
            return "로그인 실패"
예제 #15
0
파일: app.py 프로젝트: TomTheHuman/capstone
def get_monthly():
    try:
        connection = db.get_db()
        connection.connect()
        if connection.is_connected():
            print("Fetching brand totals data...", file=sys.stdout)
            data = db.get_data("month-totals", con=connection).to_json(orient="records", date_format="iso")
            connection.close()
            return {'data': json.loads(data)}


    except Error as e:
        return "Error fetching table..."
예제 #16
0
def write_data(id, question_id):
    """从数据库获取数据并写入data_dir目录下对应的文件"""
    try:
        data_path = os.path.join(config.data_dir, str(question_id))
        # low_level()
        os.mkdir(data_path)
    except OSError as e:
        if str(e).find("exist" or "已存在") > 0:  # 文件夹已经存在
            # return
            # print('exist')
            return False
        else:
            logging.error(e)
            return False
    # print('hello')
    data_num = get_data_count(question_id)
    # print(data_num)
    all_data = get_data(question_id)
    for data in all_data:
        try:
            in_path = os.path.join(config.data_dir, str(question_id),
                                   'data%s.in' % data_num)
            out_path = os.path.join(config.data_dir, str(question_id),
                                    'data%s.out' % data_num)
        except KeyError as e:
            logging.error(e)
            return False
        try:
            # low_level()
            f_in = codecs.open(in_path, 'a')
            f_out = codecs.open(out_path, 'a')
            # print('already open')
            try:
                # print('start write')
                # print(all_data)
                # print(data, data[2])
                f_in.write(data[1] + "\n")
                f_out.write(data[3] + "\n")
            except:
                logging.error("%s not write data to file" % question_id)
                f_in.close()
                f_out.close()
                return False
            f_in.close()
            f_out.close()
        except OSError as e:
            logging.error(e)
            return False
        data_num = data_num - 1
    # print('success')
    return True
예제 #17
0
def write_on_redis(querysql, type):
    try:
        redisConnection = redis.ConnectionPool(host=config.get('redis', 'redis_ip'),
                                               port=int(config.get('redis', 'redis_port')),
                                               db=int(config.get('redis', 'redis_db')))
        redisContext = redis.Redis(connection_pool=redisConnection)

        minHotMark = rank_algorithm.standard_mark()
        print ("最小的值为:"+str(minHotMark))

        dataset = db.get_data(querysql, type)

        for k, v in dataset.items():
            hotPost = []

            if len(v) > 10:
                score = {}

                for post in v:
                    # print(rank_algorithm.hot(post[13], post[3], post[9], post[7]))
                    scoreNum = rank_algorithm.hot(post[13], post[3], post[9], post[7])
                    if scoreNum >= minHotMark:
                        if scoreNum not in score:
                            score[scoreNum] = []
                            score[scoreNum].append(post)
                        else:
                            score[scoreNum].append(post)
                d = []
                for key in score.keys():
                    d.append(key)

                count = 0
                sortdata = quick_max_k.qselect(d, MAX_K)
                for sortk in sortdata[::-1]:
                    for p in score[sortk][::-1]:
                        if (count >= 10):
                            break

                        hotPost.append(convert_to_json(p))

                        count = count + 1
                print(k + '_hot_post'+json.dumps(hotPost, separators=(',', ':')))

                redisContext.set(k + '_hot_post', json.dumps(hotPost, separators=(',', ':')))


    except redis.ConnectionError as err:
        print("connect redis' failed.")
        print("Error: {}".format(err.msg))
예제 #18
0
def load_ads(scraper, db_conn):
    ads = list()
    GROUP_SIZE = 10
    for adid in db.get_data(db_conn):
        a = scraper.get_ad(adid[0])
        if not (a):
            continue
        ads.append(a.to_tuple())
        if len(ads) == GROUP_SIZE:
            db.insert_data(conn=db_conn, data=ads)
            db.delete_data(conn=db_conn, ids=[(ad[0], ) for ad in ads])
            ads = list()
        time.sleep(1)
    db.insert_data(conn=db_conn, data=ads)
    db.delete_data(conn=db_conn, ids=[(ad[0], ) for ad in ads])
예제 #19
0
def shipping(message):
    chatIDs.append(cd.cooldownTime(message.chat.id, message.date))
    users = db.get_data()
    rnd = random.randint(0, db.get_count() - 1)
    left_dog_hand = users[rnd][1]
    rnd = random.randint(0, db.get_count() - 1)
    right_dog_hand = users[rnd][1]
    bot.send_message(message.chat.id, "Море волнуется раз")
    bot.send_message(message.chat.id, "Море волнуется два")
    bot.send_message(message.chat.id, "Море волнуется три")
    bot.send_message(
        message.chat.id, "И в любовной паре замирают " + left_dog_hand +
        " + " + right_dog_hand + " = ♥️")
    text.out_white(
        convertTime(message.date) + " | " + message.from_user.first_name +
        " " + message.from_user.last_name + ": " + left_dog_hand + " + " +
        right_dog_hand + " = <3")
예제 #20
0
def main(db_path,data_format):
    conn = db.set_connection(db_path)

    for quest,sql in sorted(questions.q.items()):
        data = db.get_data(conn, sql)

        if (data_format == 'json'):
            format.return_json(data,quest)

        elif (data_format == 'xml'):
            format.return_xml(data,quest)

        elif (data_format == 'csv'):
            format.return_csv(conn,quest,sql)

        elif (data_format == 'table'):
            format.return_table(conn,quest,sql)

    conn.close()
예제 #21
0
def index():
    context = {}
    symbol = request.args.get('symbol')
    start = request.args.get('start')
    end = request.args.get('end')
    if symbol and start and end:
        start = datetime.datetime.strptime(start, '%Y-%m-%d').date()  # задаем временной промежуток
        end = datetime.datetime.strptime(end, '%Y-%m-%d').date()

        year = datetime.datetime.now().year
        if not start:
            start = datetime.date(year, 1, 1)
        if not end:
            end = datetime.date(year, 12, 31)
        data = get_data(symbol, start, end)
        context['data'] = data['data']
        context['symbol'] = symbol
        context['year'] = year
    return render_template('index.html', **context)
예제 #22
0
파일: Main.py 프로젝트: ap13p/AlbumerWX
 def __list_judul_clicked(self, evt):
     self.__set_title(str(evt.GetEventObject().GetStringSelection()))
     for i in db.get_data(evt.GetEventObject().GetStringSelection().split(' - ')[1]):
         self.lirik_viewer.ChangeValue(i[2])
예제 #23
0
파일: main.py 프로젝트: jendyren/emission
def getInfo():
    data = request.get_json()['parts']
    userid = request.cookies.get('userID')
    re = db.get_data(userid, data)
    return jsonify(re)
예제 #24
0
def meetings(meeting_id):
    # deel()
    data = get_data()
    resp = jsonify(json.loads(data[0]))
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp
예제 #25
0
def draw(message):
    if message.from_user.id == config.admin_id:
        bot.send_message(message.chat.id, str(db.get_data()))
        text.draw_data()
예제 #26
0
파일: app.py 프로젝트: MDLGH48/hcrm
def get_user_data():
    user_id = jwt.decode(request.headers.get('token')[1:-1],
                         app.config['SECRET_KEY'],
                         algorithms='HS256')["user"]
    return jsonify(get_data(user_id))
예제 #27
0
def add():
    data = db.get_data()
    return render_template('add.html', data=data, loggedIn=isLoggedIn())
예제 #28
0
def run_every_10_minutes():
    print("task run at {}".format(datetime.now()))
    get_data(url_home, categories)
예제 #29
0
import os
import face_recognition
from cv2 import cv2
import numpy as np
from db import get_data

dirname = os.path.dirname(__file__) + 'known/'

video_capture = cv2.VideoCapture(0)
row_data = get_data()
known_face_encodings = []
known_face_names = []
known_ages = []

for dic in row_data:
    known_face_names.append(dic['Name'] + ' ' + dic['Surname'])
    known_ages.append(dic['Age'])
    filename = os.path.join(dirname, dic['Path'])
    temp_image = face_recognition.load_image_file(filename)
    known_face_encodings.append(face_recognition.face_encodings(temp_image)[0])

# Initialize some variables
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True
while True:
    ret, frame = video_capture.read()

    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
예제 #30
0
        y = datetime.datetime.now().year
        start, end = datetime.date(y, 1, 1), datetime.date(y, 12, 31)

    #print('Данная программа выводит максимальное значение для цены закрытия по месяцам.')
    if args.file:
        if args.indicator:
            indicator_read_file(args.file)
        if args.max:
            process(load_data_file(args.file, start, end))  # функция выполняет обработку файла
    elif args.symbol:
        if args.indicator:
           indicator_read_net(args.symbol)
        if args.max:
            process(load_data_network(args.symbol, start, end))  # читать данные по сети
        if args.data_base:
            data = get_data(args.symbol, start, end)
            write_data(data)


    #запись в файл
    try:
        if args.save():
            write_file('out.txt')
    except:
        logging.info("Не удалось записать в файл")





예제 #31
0
 def get(self, server_name=None, f_date=None, t_date=None):
     get_data(f_date, t_date, server_name)
예제 #32
0
 def lista(self):
     print("------------------")
     print("Lista de contactos")
     print("------------------")
     get_data()