def time_check(m: discord.Message): if m.author == ctx.author and m.channel == ctx.channel is False: return False try: time_parser(m.content) except ParserError: return False return True
def parse_data(path: Path) -> pd.DataFrame: cols = ["timestamp", "user", "message"] rows = [] parser = time_parser(info=parserinfo(dayfirst=True)) line_regex = re.compile( "(.+)\\s(\\d{1,2}:\\d{2}.*?)\\s+-\\s+(.+?):\\s+(.+)") last_message = None multiline = False with open(str(path), "r", encoding="utf-8") as file: for line in file: match = line_regex.match(line) if match: if multiline: # print(last_message) # print("-" * 30) rows[-1][2] = last_message multiline = False timestamp = parser.parse(f"{match[1]} {match[2]}") rows.append([timestamp, match[3], match[4]]) last_message = match[4] else: if last_message is not None: if not multiline: multiline = True last_message = f"{last_message}{line}" conversation_data = pd.DataFrame(data=rows, columns=cols) return conversation_data
def clean_empty_queues(base_url, regex_pattern, queue_idle_minutes, force_delete=False): start = time.time() pattern = re.compile(regex_pattern) payload = { 'name': regex_pattern, 'use_regex': 'true' } try: response = requests.request("GET", base_url + '/api/queues', params=payload) total = 0 matched = 0 deleted = 0 for i, queue in enumerate(response.json()): total += 1 name = queue['name'] consumers = queue.get('consumers') if consumers and consumers != 0: logger.debug('%s has %s consumers, skipping' % (name, consumers)) continue messages = queue.get('messages') if messages and messages != 0: logger.debug('%s has %s messages, skipping' % (name, messages)) continue messages_unacknowledged = queue.get('messages_unacknowledged') if messages_unacknowledged and messages_unacknowledged != 0: logger.debug('%s has %s unacked messages, skipping' % (name, messages_unacknowledged)) continue idle_since = time_parser(queue['idle_since']) if 'idle_since' in queue else datetime.datetime.now() if idle_since and (idle_since.now() - idle_since).total_seconds() > queue_idle_minutes * 60: logger.debug('%s is not idle, skipping' % name) continue vhost = '%2f' if (queue['vhost'] == '/') else queue['vhost'] if pattern.match(name): matched += 1 idle_minutes = int((idle_since.now() - idle_since).total_seconds() / 60) logger.debug('queue "%s" has been inactive for %d minutes' % (queue, idle_minutes)) delete_url = base_url + '/api/queues/' + vhost + '/' + name delete_url += '' if force_delete else '?if-empty=true:if-unused=true' logger.info('deleting queue "%s"' % delete_url) response = requests.request("DELETE", delete_url) if 200 <= response.status_code < 300: deleted += 1 else: logger.error('problem deleting queue "%s": %s' % (name, response.text)) logger.debug('%d queues processed, %d matched parameters, %d deleted' % (total, matched, deleted)) except Exception as error: logger.exception(error) else: logger.info("execution took %s" % (time.time() - start))
def get_rooms_data_frame(room_details_file): """ It simply extract data from input file in a way that every record/line has only one time slot with other details such as room_no, capacity, time_slot (start_time & end_time) :param room_details_file: relative path of input data file :return: extracted dataframe """ df = pd.DataFrame( columns=["room_no", "capacity", "start_time", "end_time"]) with open(room_details_file, "r") as f: for line_number, line in enumerate(f.readlines()): if line.endswith("\n"): line = line[:-1] delimit_split_array = re.split(",", line) if len(delimit_split_array) % 2 != 0: raise ValueError( "Incorrect data in provided file, number of elements in each row must be even [line_number: {}]" .format(line_number)) room_no = delimit_split_array[0] capacity = int(delimit_split_array[1]) start_time, end_time = [], [] for index in range(2, len(delimit_split_array), 2): start_time.append( time_parser(delimit_split_array[index]).time()) end_time.append( time_parser(delimit_split_array[index + 1]).time()) number_of_time_availability_durations = len(start_time) df = pd.concat([ df, pd.DataFrame({ "room_no": [room_no] * number_of_time_availability_durations, "capacity": [capacity] * number_of_time_availability_durations, "start_time": start_time, "end_time": end_time }) ]) return df
def find_closest_meeting_room(requirement, room_details_file="./resources/rooms.csv"): """ It is the main function which executes all the steps (extracting data, transforming data and extracting available meeting room) :param requirement: input string :param room_details_file: data_file which has list of room details :return: closest room number [for tie scenarios, it will return any value] """ current_floor, team_size, meeting_start_time, meeting_end_time = requirement.split( DELIMITER) meeting_start_time, meeting_end_time = time_parser( meeting_start_time).time(), time_parser(meeting_end_time).time() current_floor = int(current_floor) team_size = int(team_size) rooms_data_frame = get_rooms_data_frame(room_details_file) # print(rooms_data_frame) rooms_data_frame = transform_data_frame(rooms_data_frame) # print(rooms_data_frame) return get_closest_room_no(rooms_data_frame, current_floor=current_floor, team_size=team_size, meeting_start_time=meeting_start_time, meeting_end_time=meeting_end_time)
m = await ctx.send( "What time of day should I send the birthday message? Please use the UTC time, for" " example `12AM` for midnight or `7:00`. I will ignore any invalid input. I will" " ignore minutes.\n\nYou have 5 minutes.") try: ret = await self.bot.wait_for("message", check=time_check, timeout=300) except asyncio.TimeoutError: await ctx.send( f"Took too long to react, cancelling setup. Run `{ctx.clean_prefix}bdset" " interactive` to start again.") return full_time = time_parser(ret.content) full_time = full_time.replace(tzinfo=datetime.timezone.utc, year=1, month=1, day=1) midnight = datetime.datetime.now(tz=datetime.timezone.utc).replace( year=1, month=1, day=1, hour=0, minute=0, second=0, microsecond=0) time_utc_s = int((full_time - midnight).total_seconds()) await ctx.trigger_typing() async with self.config.guild(ctx.guild).all() as conf: conf["time_utc_s"] = time_utc_s conf["message_w_year"] = message_w_year