Esempio n. 1
0
 def from_db_object(self, db_object):
     return SampleStamp(mac=Mac(db_object['mac']),
                        location=Location(x=db_object['location']['x'],
                                          y=db_object['location']['y'],
                                          z=db_object['location']['z']),
                        start_time=Time(int(db_object['start_time'])),
                        end_time=Time(int(db_object['end_time'])))
Esempio n. 2
0
 def fetch_measures(self):
     end = Time()
     start = Time(end.millis - self.fetch_seconds * 1000)
     apdatas = self.ap_data_dao.get_for_time_range(start,
                                                   end,
                                                   asc=False,
                                                   query=self.query)
     measures = self.make_measures(apdatas)
     return measures
Esempio n. 3
0
 def run(self):
     start = Time()
     for step in self.steps:
         result = step.simulate_step()
         if result == 200:
             self.sent += 1
         else:
             print("error " + result)
     end = Time()
     print("simulator sent {} jsons successfully".format(self.sent))
     return start, end
Esempio n. 4
0
 def from_db_object(self, db_object):
     return Position(mac=Mac(db_object['mac']),
                     location=Location(x=db_object['location']['x'],
                                       y=db_object['location']['y'],
                                       z=db_object['location']['z']),
                     created_at=Time(int(db_object['created_at'])),
                     _id=db_object['_id'])
Esempio n. 5
0
    def post(self):
        api_assert(self.body['data'], 400, 'empty data')

        try:
            ap_datas = []

            router_mac = Mac.correct(self.body['apMac'])
            signal = Signal(band='2.4', channel=self.body['band'])
            created_at = Time(int(self.body['time']))

            for item in self.body['data']:
                device_mac = Mac.correct(item['clientMac'])
                rssis = {}
                if item.get('rss1') is not None:
                    rssis['1'] = RSSI(float(item['rss1']))
                if item.get('rss2') is not None:
                    rssis['2'] = RSSI(float(item['rss2']))
                if item.get('rss3') is not None:
                    rssis['3'] = RSSI(float(item['rss3']))

                if len(rssis) > 0:
                    ap_datas.append(
                        APData(router_mac=router_mac,
                               device_mac=device_mac,
                               created_at=created_at,
                               rssis=rssis,
                               signal=signal))

            for ap_data in ap_datas:
                self.ap_data_dao.save(ap_data)
        except DBException as e:
            raise APIError(500, e.message)
        return 'ok'
Esempio n. 6
0
 def start_new_benchmark(self):
     with self.lock:
         if not self.check_current_benchmark_inactive():
             raise BenchmarkException("Benchmark already in progress")
         self.ping_listener()
         self.current_benchmark = Process(target=run_benchmark)
         self.current_benchmark.start()
         self.benchmark_start_time = Time()
Esempio n. 7
0
def create():
    form = NovoTimeForm()
    if form.validate_on_submit():
        time = Time(nome=form.nome_time.data, escudo=form.escudo.data)
        db.session.add(time)
        db.session.commit()
        return redirect(url_for('times.index'))
    return render_template('novotime.html', title='Novo Time', form=form)
Esempio n. 8
0
 def from_db_object(self, db_object):
     return APData(
         router_mac=Mac(db_object['router_mac']),
         device_mac=Mac(db_object['device_mac']),
         created_at=Time(int(db_object['created_at'])),
         rssis={k: RSSI(float(v))
                for k, v in db_object['rssis'].items()},
         signal=Signal(channel=int(db_object['signal']['channel']),
                       band=db_object['signal']['band']),
         _id=db_object['_id'])
Esempio n. 9
0
 def setTime():
     if ("username" in session):
         cube = request.args.get("cube")
         time = request.args.get("time")
         displayTime = request.args.get("displayTime")
         scramble = request.args.get("scramble")
         newTime = Time(session["id"], cube, time, displayTime, scramble)
         db.session.add(newTime)
         db.session.commit()
         return "Tiempo grabado con exito"
     else:
         return "Primero inicia sesion y luego vemos"
Esempio n. 10
0
def enter_time(name, total_time):
    """
    Create a Time entry in the Time database
    :param name: Client Name
    :param start: Datetime
    :param end: Datetime
    :return: None
    """
    session = make_session()
    entry = Time(name=name, total_time=total_time)
    session.add(entry)
    session.commit()
Esempio n. 11
0
def enter_multiple_times(time_dictionary):
    """
    Create multiple Time entries in the Time database
    :param dictionary: Dictionary formatted to match the Time class
    :return: None
    """
    session = make_session()
    for entry in time_dictionary.items():
        name, total_time = entry
        new_entry = Time(name=name, total_time=total_time)
        session.add(new_entry)
    session.commit()
Esempio n. 12
0
def incluir_times():
    resposta = jsonify({"resultado": "ok", "detalhes": "ok"})
    dados = request.get_json()
    try:
        novo = Time(**dados)
        db.session.add(novo)
        db.session.commit()

    except Exception as e:
        resposta = jsonify({"resultado": "erro", "detalhes": str(e)})

    resposta.headers.add("Access-Control-Allow-Origin", "*")
    return resposta
Esempio n. 13
0
    def authenticate(self, username, password):

        userInfo = User.query.filter_by(U_LoginName=username).first()
        if userInfo is None:
            return jsonify(common.falseReturn('', '找不到用户'))
        else:
            if userInfo.verify_password(password):
                login_time = datetime.datetime.now().strftime(
                    "%Y-%m-%d %H:%M:%S")
                save = Time(U_id=userInfo.U_id, LoginTime=login_time)
                db.session.add(save)
                db.session.commit()
                token = self.encode_token(userInfo.U_id, login_time)
                return jsonify(common.trueReturn(token.decode(), '登录成功'))
            else:
                return jsonify(common.falseReturn('', '密码不正确'))
Esempio n. 14
0
def calculate_statistics(number_of_packets_for_simulation, packets,
                         time_of_service, average_time_between_packets,
                         confidence_range):
    print("**********************")
    print("CALCULATING STATISTICS")
    print("**********************")
    # l - LAMBDA - intensywnosc naplywu klientow
    LAMBDA = 1 / average_time_between_packets
    # u - intensywnosc obslugi klientow - odwrotnosc czasu obslugi klienta
    u = 1 / time_of_service
    # p - srednie obciazenie systemu = LAMBDA/U
    p = LAMBDA / u
    teoretical_average_delay = 0
    if p != 1:
        # Sredni czas oczekiwania w systemie - kalkulacje teoretyczne
        teoretical_average_delay = p / (LAMBDA * (1 - p))
        print("AVERAGE TEORETICAL TIME OF WAITING IN QUEUE: ",
              teoretical_average_delay)
    else:
        print("AVERAGE TEORETICAL TIME OF WAITING IN QUEUE: INF")

    print("PRACTICAL CALCULATIONS")
    #rozbieg
    packets_less = packets[round(len(packets) * 0.1):]
    # Sredni czas oczekiwania w kolejce - kalkulacje praktyczne
    practical_average_time_of_delay = 0
    for i in packets:
        delay = i.time_finish_of_service - i.time_of_arrive
        if delay > 0:
            practical_average_time_of_delay += delay
    practical_average_time_of_delay /= (number_of_packets_for_simulation - 1)
    print("AVERAGE PRACTICAL TIME OF WAITING IN SYSTEM ",
          practical_average_time_of_delay)
    delays = []
    for i in packets:
        delay = i.time_finish_of_service - i.time_of_arrive
        if delay > 0:
            delays.append(i.time_finish_of_service - i.time_of_arrive)
    confidence_delay, min_delay, max_delay = calculate_confidence(
        delays, confidence_range)
    return Time(practical_average_time_of_delay, teoretical_average_delay,
                confidence_delay, min_delay, max_delay)
Esempio n. 15
0
def times(request, prid):
    global months
    if request.method == "POST":
        lform = request.POST
        d = lform['days']
        m = lform['months']
        h = lform['hour']
        weekday = lform['weekday']
        print d, m, h, weekday, 'printing!'
        time = Time()
        time.d = d
        time.m = m
        time.h = h
        time.weekday = weekday
        time.project = Project.objects.get(id=int(prid))
        time.save()
    pr = Project.objects.get(id=prid)
    times = Time.objects.filter(project=pr)
    # print times
    return render(request, 'time.html', {
        'days': range(1, 32),
        'times': times,
        'prid': prid
    })
Esempio n. 16
0
async def handle_ban_reaction(
    reaction: discord.Reaction,
    user: discord.User,
    ctx: MessageContext,
) -> HandlerStatus:
    is_ban_emoji = not isinstance(reaction.emoji,
                                  str) and reaction.emoji.name == "BAN"
    is_april_fools = datetime.datetime.today().date() == datetime.date(
        2022, 4, 1)

    # Special feature for people trying to ban the bot itself
    if is_ban_emoji and ctx.client.user.id == ctx.message.author.id:
        my_name = ctx.client.user.name
        await reaction.message.channel.send(
            f"Who *dares* try to ban the mighty {my_name}?!")
        await ban.ban(
            ctx,
            target=DiscordUser(user.id),
            timer=Time("1hr"),
            ban_as_bot=True,
        )
        return HandlerStatus(Status.Success)

    if is_ban_emoji and is_april_fools:
        await ban.ban(
            ctx,
            target=DiscordUser(user.id),
            timer=Time("1hr"),
            ban_as_bot=True,
        )
        return HandlerStatus(Status.Success)

    # Only ban a user if we've hit the reaction threshold
    # TODO: Make threshold configurable per-server
    if not is_ban_emoji or reaction.count != ctx.server_ctx.ban_reaction_threshold:
        return HandlerStatus(Status.Invalid)

    # Check if this message has been banned before
    banned_before = db_helper.has_message_been_banned(
        ctx.db_conn, reaction.message.guild.id, reaction.message.id)
    if banned_before:
        logging.warning(
            "New ban reaction on message but it was banned before.")
        return HandlerStatus(Status.Invalid)

    # We need to record that this message has now been banned
    db_helper.record_banned_message(ctx.db_conn, reaction.message.guild.id,
                                    reaction.message.id)

    # Check if the user was turbo banned
    elapsed = datetime.datetime.now() - reaction.message.created_at
    turbo_ban = elapsed.total_seconds(
    ) <= ctx.server_ctx.turbo_ban_timing_threshold

    if turbo_ban:
        emojis = {e.name: f"<:{e.name}:{e.id}>" for e in ctx.client.emojis}
        turbo = ["T_", "U_", "R_", "B_", "O_"]
        turbo_str = "".join(emojis[s] for s in turbo)
        banned = ["B_", "A_", "N_", "N_", "E_", "D_"]
        banned_str = "".join(emojis[s] for s in banned)
        turbo_ban_msg = f"{turbo_str} {banned_str}"
        await reaction.message.channel.send(turbo_ban_msg,
                                            reference=reaction.message)
        await ban.ban(
            ctx,
            target=DiscordUser(reaction.message.author.id),
            timer=Time("5hr"),
            ban_as_bot=True,
        )
        return HandlerStatus(Status.Success)

    await reaction.message.channel.send("Bro", reference=reaction.message)
    # Sleep 3 seconds to build suspense
    await asyncio.sleep(3)
    await ban.ban(
        ctx,
        target=DiscordUser(reaction.message.author.id),
        timer=Time("1hr"),
        ban_as_bot=True,
    )
    return HandlerStatus(Status.Success)
Esempio n. 17
0
def drop_data(file: str):
    '''Drop data from `file`.

    Arguments:
    ==========
        file: String

    Returns:
    ========
        None
    '''
    os.remove(file)


# Cache data
if os.path.exists(data_file):
    context, cities, airline, t = read_data(data_file)
else:
    context = Context()
    t = Time()
    cities = [City(city_capacity()) for i in range(city_number)]

    for city in cities:
        city.init_airport(airport_capacity, aircraft_capacity, aircraft_speed,
                          aircraft_capacity_ratio, people_number_ratio)

    airline = Airline(cities, time_limit, distance_to_weights)

    write_data(data_file, context, cities, airline, t)
Esempio n. 18
0
 def send(self):
     self.time = Time().millis
     res = requests.post(self.API_URL, json=self.__dict__)
     return res.status_code
Esempio n. 19
0
async def roll(ctx: MessageContext) -> None:
    """Roll a die for the server based on the current roll"""
    guild_id = ctx.server_ctx.guild_id
    next_roll = ctx.server_ctx.current_roll
    username = ctx.message.author.name

    last_roll_time = db_helper.get_last_roll_time(ctx.db_conn, guild_id,
                                                  ctx.discord_id)
    now = datetime.datetime.now()

    if last_roll_time is not None:
        last_roll_str = last_roll_time.strftime("%Y-%m-%d %I:%M:%S %p")
        logging.info(f"{ctx.discord_id} last rolled at {last_roll_str}")

        last_roll_delta = int((now - last_roll_time).total_seconds() // 3600)
        timeout = ctx.server_ctx.roll_timeout_hours
        if last_roll_delta < timeout:
            await ctx.channel.send(
                f"<@{ctx.discord_id}> last rolled at {last_roll_str} ({last_roll_delta} hours ago).\n"
                f"This server only allows rolling once every {timeout} hours.\n"
            )
            ban_time = Time("1hr")
            await ban.ban(ctx,
                          DiscordUser(ctx.discord_id),
                          ban_time,
                          ban_as_bot=True)
            # Bail early - don't allow rolling
            return

    logging.info(
        f"Next roll in server({guild_id}) for {username} is {next_roll}")

    # Finally, actually roll the die
    roll = random.randint(1, next_roll)
    db_helper.record_roll(ctx.db_conn, guild_id, ctx.message.author.id, roll,
                          next_roll)
    await ctx.channel.send(f"```# {roll}\nDetails: [d{next_roll} ({roll})]```")
    logging.info(f"{username} rolled a {roll} (d{next_roll})")

    if roll == 1:
        await ctx.channel.send("Lol, you suck")
        ban_time = Time(f"{next_roll}hr")
        await ban.ban(ctx,
                      DiscordUser(ctx.discord_id),
                      ban_time,
                      ban_as_bot=True)
    elif roll == next_roll - 1:
        s = ctx.server_ctx.critical_failure_msg
        if s != "":
            await ctx.channel.send(f"<@{ctx.discord_id}>: {s}")
        else:
            await ctx.channel.send(
                f"<@{ctx.discord_id}>: gets to rename the chat channel!")
    elif roll == next_roll:
        # Increment the current roll
        ctx.server_ctx.current_roll = next_roll + 1
        logging.info(f"Next roll in server({guild_id}) is now {next_roll + 1}")

        s = ctx.server_ctx.critical_success_msg
        if s != "":
            await ctx.channel.send(f"<@{ctx.discord_id}>: {s}")
        else:
            await ctx.channel.send(
                f"<@{ctx.discord_id}>: gets to rename the server!")

    # If the user has roll reminders set up, await that now
    # I'm not sure why, but we need to reload here
    ctx.server_ctx.reload()
    roll_timeout = ctx.server_ctx.roll_timeout_hours
    user_id = ctx.discord_id
    if roll_timeout > 0 and ctx.server_ctx.should_remind(user_id):
        logging.info(
            f"Sleeping {roll_timeout} hours then reminding {user_id} to roll")
        await asyncio.sleep(roll_timeout * 3600)
        await roll_remind.send_roll_reminder(ctx, ctx.message.author)
Esempio n. 20
0
def insert_test_data():
    with open('test_data.json', 'r', encoding='utf8') as _file:
        data = json.load(_file)
    all_objects = []

    week_days = [
        WeekDay(id=_id, day_name=day_name)
        for _id, day_name in [(1, 'Понедельник'), (2, 'Вторник'), (
            3,
            'Среда'), (4,
                       'Четверг'), (5,
                                    'Пятница'), (6,
                                                 'Суббота'), (7,
                                                              'Воскресенье')]
    ]
    all_objects.extend(week_days)

    times = [
        Time(id=id_time[0], time=id_time[1])
        for id_time in [(1, tim(8)), (2, tim(10)), (3, tim(12)), (
            4, tim(14)), (5, tim(16)), (6, tim(18)), (7, tim(20)), (8,
                                                                    tim(22))]
    ]
    all_objects.extend(times)

    goals = \
        [Goal(id=int(goal_id), value=goal_data[0], emoji=goal_data[1]) for goal_id, goal_data in data['goals'].items()]
    all_objects.extend(goals)

    teachers = []
    lessons = []
    lesson_id = 1
    for teacher_dict in data['teachers']:
        teacher_ = Teacher(
            id=int(teacher_dict['id']) + 1,
            name=teacher_dict['name'],
            about=teacher_dict['about'],
            rating=teacher_dict['rating'],
            picture=teacher_dict['picture'],
            price=teacher_dict['price'],
            goals=list(
                filter(
                    lambda x: x.id in [int(i) for i in teacher_dict['goals']],
                    goals)))
        teachers.append(teacher_)
        for day_id, time_status in teacher_dict['free'].items():
            for _time, status in time_status.items():
                _time = tim(int(_time.split(':')[0]))
                _time_id = list(filter(lambda x: x.time == _time, times))[0].id
                lesson = Lesson(id=lesson_id,
                                teacher_id=teacher_.id,
                                day_name_id=int(day_id),
                                time_id=_time_id,
                                status=status)
                lessons.append(lesson)
                lesson_id += 1

    all_objects.extend(teachers)
    all_objects.extend(lessons)

    db.session.add_all(all_objects)
    db.session.commit()
Esempio n. 21
0
def handle_time_creation(message, broker):
    broker.db["time"] = Time()