Ejemplo n.º 1
0
def main():
    # установка соединения
    sock = socket.socket()
    utils.connection(sock)
    # проверка списка модераторов
    start_new_thread(utils.fill_moderator_list, ())
    # установка пформы для прообразования сообщений из чата
    chat_message = re.compile(r"^:\w+!\w+@\w+\.tmi\.twitch\.tv PRIVMSG #\w+ :")
    # пропуск приветствия Твитча
    while True:
        res = str(sock.recv(1024))
        if "End of /NAMES list" in res:
            break
    # основной цикл работы с переадресовкой на вызванные функции
    while True:
        # получение сообщения из чата
        try:
            res = sock.recv(1024).decode()
        except Exception:
            print("Can't recive message")
        # проверка сообщения на пинг
        if res == "PING :tmi.twitch.tv\r\n":
            sock.send("POND :tmi.twitch.tv\r\n".encode())
        # обработка всех остальных сообщений кроме пинга
        else:
            try:
                username = re.search(r"\w+", res).group(0)
                message = chat_message.sub("", res)
                message = message.strip()
                utils.check_command(sock, username, message)
            except Exception as msg:
                print("#ERROR", msg)
Ejemplo n.º 2
0
def method_conn():
  conn, cur = connection()
  data_json = request.get_json()
  
  i_d = data_json['id']
  firstname = data_json['firstname']
  lastname = data_json['lastname']
  email = data_json['email']
  pass_word = data_json['password']

  select_query = 'select email_id from details where email_id=%s;'
  valu_qur = (email,)
  cur.execute(select_query, valu_qur)
  email_data = cur.fetchall()
  print(email_data)
  print(email)

   

  if len(email_data) == 0 :
     cur_query = 'insert into details(usr_id, first_name, last_name, email_id, pass_word) values(%s, %s, %s, %s, %s);'
     qur_values = (i_d, firstname, lastname, email, pass_word)
     cur.execute(cur_query, qur_values)
     conn.commit()
     print('data is sent')
     return jsonify(message='data sent')

  else:
     print('email is already exixts')
     return jsonify(message='email is already exists')
Ejemplo n.º 3
0
        password='******',
    )
    u, result = User.register(form)
    form['username'] = '******'
    User.register(form)

    form = dict(
        title='test todo',
        user_id=u.id,
    )
    utils.log('todo form', form)
    t = Todo.new(form)

    form = dict(
        content='weibo',
        user_id=u.id,
    )
    w = Weibo.new(form)
    form = dict(content='comment', user_id=u.id, weibo_id=w.id)
    w = Comment.new(form)


if __name__ == '__main__':
    c = utils.connection()
    try:
        reset(c)
        create_tables(c)
        fake_data()
    finally:
        c.close()
def run_scenario(scenario_id, args=None):
    
    logd = create_logger(appname='{} - {} - details'.format(args.app_name, scenario_id),
                         logfile=join(args.scenario_log_dir,'scenario_{}_details.txt'.format(scenario_id)),
                         msg_format='%(asctime)s - %(message)s')
    logp = create_logger(appname='{} - {} - progress'.format(args.app_name, scenario_id),
                         logfile=join(args.scenario_log_dir, 'scenario_{}_progress.txt'.format(scenario_id)),
                         msg_format='%(asctime)s - %(message)s')
    
    logd.info('starting scenario {}'.format(scenario_id))
    
    # get connection, along with useful tools attached
    conn = connection(args, scenario_id, args.template_id, logd)
    
    # time steps
    ti = datetime.strptime(args.initial_timestep, args.timestep_format)
    tf = datetime.strptime(args.final_timestep, args.timestep_format)
    dates = [date for date in rrule.rrule(rrule.MONTHLY, dtstart=ti, until=tf)]
    
    timestep_dict = OrderedDict()
    conn.OAtHPt = {}
    for date in dates:
        oat = date.strftime(args.timestep_format)
        hpt = date.strftime(args.hydra_timestep_format)
        timestep_dict[date] = [hpt, oat]
        conn.OAtHPt[oat] = hpt
        
    template_attributes = conn.call('get_template_attributes', {'template_id': conn.template.id})
    attr_names = {}
    for ta in template_attributes:
        attr_names[ta.id] = ta.name
        
    # create the model
    instance = prepare_model(model_name='OpenAgua',
                             network=conn.network,
                             template=conn.template,
                             attr_names=attr_names,
                             timestep_format=args.timestep_format,
                             timestep_dict=timestep_dict)
    
    logd.info('model created')
    opt = SolverFactory(args.solver)
    results = opt.solve(instance, tee=False)
    #logd.info('model solved')

    old_stdout = sys.stdout
    sys.stdout = summary = StringIO()
    results.write()
    sys.stdout = old_stdout
    
    logd.info('model solved\n' + summary.getvalue())
    
    if (results.solver.status == SolverStatus.ok) and (results.solver.termination_condition == TerminationCondition.optimal):
        # this is feasible and optimal
        logd.info('Optimal feasible solution found.')
        outputnames = {'S': 'storage', 'I': 'inflow', 'O': 'outflow'}
        #outputnames = {'I': 'inflow', 'O': 'outflow'}
        result = conn.save_results(instance, outputnames)
        logd.info('Results saved.')
    elif results.solver.termination_condition == TerminationCondition.infeasible:
        logd.info('WARNING! Problem is infeasible. Check detailed results.')
        # do something about it? or exit?
    else:
        # something else is wrong
        logd.info('WARNING! Something went wrong. Likely the model was not built correctly.')    
    
    # Still we will report that the model is complete...
    if args.foresight == 'perfect':
        msg = 'completed timesteps {} - {} | 1/1'.format(ti, tf)
        logd.info(msg)
        logp.info(msg)
    
    # ===========================
    # start the per timestep loop
    # ===========================
   
    #T = len(dates)
    #for t, date in enumerate(dates):
        
        # ===========================
        # prepare the time steps to use in the optimization run
        # ===========================        

        # ===========================
        # prepare the inflow forecast model
        # ===========================

        # For now, forecast based on mean monthly inflow at each catchment node
        # However, this can be changed in the future

        # ===========================
        # run the model
        # ===========================
        
        #if new_model:
            #model = create_model(data)
            #instance = model.create_instance()            
        #else:
            #instance = update_instance(instance, S0, inflow)
            #instance.preprocess()
            
        # solve the model
        #results = solver.solve(instance)
        
        # load the results
        #instance.solutions.load_from(results)
        
        # set initial conditions for the next time step
        #S0 = instance.S[isIDs[0]].value
        #if S0 is None:
            #S0 = 0.0
            
        # ===========================
        # save results to memory
        # ===========================
        
        
        #logd.info('completed timestep {} | {}/{}'.format(dt.date.strftime(date, args.timestep_format), t+1, T))
    
    # ===========================
    # save results to Hydra Server
    # ===========================
    
    
    return
Ejemplo n.º 5
0
                            :countComments,:weight,:isDolbyAtmos,
                            :isImax,:is4dx,:isPresale,:distributorId
                            WHERE NOT EXISTS(SELECT 1 FROM films WHERE movieid = :movieid)"""
        cur.execute(query, params)
    conn.commit()


def get_all_cities(con):
    query = """
    SELECT cityid from cities"""
    a = pd.read_sql(query, con)
    return a.cityid.values


if __name__ == '__main__':
    conn = utils.connection(utils.DB_ROOT)
    create_table(utils.filmps_params, 'films', conn)
    create_table(utils.cinema_params, 'cinemas', conn)
    create_table(utils.cities_params, 'cities', conn)
    create_table(utils.halls_params, 'halls', conn)
    create_table(utils.seances_params, 'seances', conn)
    df_lang = create_df_with_data('../data/languages.json')
    #print(df_lang.head(20))
    #full_languages(df_lang,conn)
    #df_film = create_df_with_data('../data/all_films.json')
    #add_producers(df_film,conn
    #add_companies(df_film, conn)
    #add_directors(df_film, conn)
    #add_genres(df_film, conn)
    #add_actors(df_film, conn)
    #country_for_film(df_film, conn)
Ejemplo n.º 6
0
  print(email)

   

  if len(email_data) == 0 :
     cur_query = 'insert into details(usr_id, first_name, last_name, email_id, pass_word) values(%s, %s, %s, %s, %s);'
     qur_values = (i_d, firstname, lastname, email, pass_word)
     cur.execute(cur_query, qur_values)
     conn.commit()
     print('data is sent')
     return jsonify(message='data sent')

  else:
     print('email is already exixts')
     return jsonify(message='email is already exists')
conn, cur = connection()
@app.route('/<int:data>/<pass_word>', methods=['GET', 'DELETE', 'PATCH'])
def methods_types(data,pass_word):
   if request.method == 'GET':
      qur_data = 'select * from details where usr_id=%s;'
      v_qu = (data,)
     
      cur.execute(qur_data,v_qu)
      cur_data = cur.fetchall()
      for data in cur_data:
         t=dict(data)
         k_v={str(i):str(j) for i,j in t.items()}
         print(k_v)
         return str(k_v)

   if request.method == 'PATCH':