Best Python code snippet using hypothesis
main.py
Source:main.py
...10 for word in words:11 if word in message:12 return True13 return False14def event_to_string(event):15 time = ""16 if "dateTime" in event["start"]:17 time = parse(event["start"]["dateTime"]).strftime("%A, %d of %B at %I:%M%p")18 else:19 time = parse(event["start"]["date"]).strftime("%A, %d of %B")20 return event["summary"] + ", " + time21def match_event(query, events):22 fuzzy_threshold_ratio = 9023 max_event = None24 max_ratio = 025 for event in events:26 ratio = fuzz.partial_ratio(event["summary"].lower(), query.lower())27 if ratio > max_ratio:28 max_ratio = ratio29 max_event = event30 if max_ratio > fuzzy_threshold_ratio:31 return max_event32 return None33plan_calendar = "rmit.edu.au_ct5j003ncdbmu1o2ga2gasu86k@group.calendar.google.com"34def parse_datetime(date):35 return parse(date).strftime("%A, %d of %B at %I:%M%p")36def parse_time(date):37 return parse(date).strftime("%I:%M%p")38def parse_date(date):39 return parse(date).strftime("%A, %d of %B")40def cleanhtml(raw_html):41 cleanr = re.compile("<.*?>")42 cleantext = re.sub(cleanr, "", raw_html.replace("<br>", "\n"))43 return cleantext44def event_time_to_string(start, end):45 if start["dateTime"]:46 return "from {} to {}".format(47 parse_datetime(start["dateTime"]), parse_time(end["dateTime"])48 )49 else:50 return "on {}".format(parse_date(start["date"]))51async def describe_event(channel, event):52 await client.send_message(53 channel,54 content="Certainly, the {} will be run {} \n Location: {}\n{}".format(55 event["summary"],56 event_time_to_string(event["start"], event["end"]),57 event["location"] if "location" in event else "Undecided",58 cleanhtml(event["description"])59 if "description" in event60 else "Description Needed",61 ),62 )63async def on_event_match(message, event):64 location_set = re.search("(?:at|in) (\d\d\.\d\d\.\d\d\d)", message.content)65 if location_set:66 room_no = location_set.group(1)67 patch_event(plan_calendar, event["id"], {"location": room_no})68 await client.send_message(69 message.channel,70 "Ok, set {} to location {}".format(event["summary"], room_no),71 )72 else:73 await describe_event(message.channel, event)74@client.event75async def on_message(message):76 name = (77 message.author.nick78 if hasattr(message.author, "nick") and message.author.nick is not None79 else message.author.name80 )81 if client.user.mentioned_in(message):82 if (83 not message.channel.is_private84 and message.author.server_permissions.administrator85 ):86 await client.send_typing(message.channel)87 events = get_upcoming(plan_calendar)88 event = match_event(message.content, events)89 if event:90 await on_event_match(message, event)91 else:92 if words_in(["plan", "event", "run", "schedule"], message.content):93 if len(events) > 0:94 upcoming = "\n".join(95 [96 event_to_string(event)97 for event in events98 if "dateTime" in event["start"]99 and "description" in event100 and "location" in event101 ]102 )103 messages = []104 counter = 0105 if len(upcoming) > 0:106 messages.append(107 "Here are the events we have planned: \n {}".format(108 upcoming109 )110 )111 else:112 messages.append(113 "We don't actually have any events completely ready to publish yet"114 )115 no_time = "\n".join(116 [117 event_to_string(event)118 for event in events119 if "dateTime" not in event["start"]120 ]121 )122 if len(no_time) > 0:123 messages.append(124 "These ones we haven't got a specific time for: \n {}".format(125 no_time126 )127 )128 no_description = "\n".join(129 [130 event_to_string(event)131 for event in events132 if "description" not in event133 ]134 )135 if len(no_description) > 0:136 messages.append(137 "These ones don't have a description: \n {}".format(138 no_description139 )140 )141 no_location = "\n".join(142 [143 event_to_string(event)144 for event in events145 if "location" not in event146 ]147 )148 if len(no_description) > 0:149 messages.append(150 "These ones don't have a location: \n {}".format(151 no_location152 )153 )154 await client.send_message(155 message.channel, content="\n\n".join(messages)156 )157 else:158 await client.send_message(message.channel, "No events planned")159 elif words_in(["meeting"], message.content):160 await client.send_typing(message.channel)161 events = get_upcoming(162 "rmit.edu.au_cqqvahbep63tttoc551ug04q88@group.calendar.google.com"163 )164 if len(events) > 0:165 upcoming = "\n".join(166 [event_to_string(event) for event in events]167 )168 counter = 0169 await client.send_message(170 message.channel,171 content="Here are the meetings we have planned: \n {}".format(172 upcoming173 ),174 )175 else:176 await client.send_message(177 message.channel, "No meetings coming up"178 )179 else:180 await client.send_message(...
fdc.py
Source:fdc.py
...41 else: # Needed only for compatibility with Python 2.642 credentials = tools.run(flow, store)43 print('Storing credentials to ' + credential_path)44 return credentials45def event_to_string(e):46 s = 'Zusammenfassung: {}\n{} - {}\nBeschreibung: {}\nLink: {}\n\n'.format(47 e['summary'], e['start']['dateTime'], e['end']['dateTime'], e.get('description', '-'),48 e['htmlLink'])49 return s50def mail(text):51 msg = EmailMessage()52 msg.set_content(text)53 # TODO add event and reason to content54 msg['Subject'] = config['mail subject']55 msg['From'] = config['mail from']56 msg['To'] = config['mail to']57 # Send the message via our own SMTP server.58 s = smtplib.SMTP(config['smtp host'])59 s.send_message(msg)60 s.quit()61def main():62 """63 Main rutine with infinite loop checkin calendar64 """65 parser = argparse.ArgumentParser(parents=[tools.argparser])66 parser.add_argument('config', type=argparse.FileType('r'), help='YAML config file')67 global args, config68 args = parser.parse_args()69 config = yaml.safe_load(args.config)70 71 credentials = get_credentials()72 http = credentials.authorize(httplib2.Http())73 service = discovery.build('calendar', 'v3', http=http)74 spaceapi_delay = datetime.timedelta(seconds=config['spaceapi delay seconds'])75 fail_state = False76 77 while True:78 now_str = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time79 eventsResult = service.events().list(80 calendarId=config['calendar id'], timeMin=now_str, maxResults=10 , singleEvents=True,81 orderBy='startTime').execute()82 events = eventsResult.get('items', [])83 84 # Filter full-day events85 events = [e for e in events if 'dateTime' in e['start']]86 # Filter based on summary regex87 events = [e for e in events if re.match(config['event summary filter'], e['summary'])]88 89 for e in events:90 # Parse dateTime91 e['start']['dateTime'] = dateutil.parser.parse(e['start']['dateTime'])92 e['end']['dateTime'] = dateutil.parser.parse(e['end']['dateTime'])93 94 if not events:95 print('No upcoming events found.')96 return97 else:98 print('Relevant event:')99 print(event_to_string(events[0]))100 now = datetime.datetime.now(pytz.utc)101 open_door_required = (events[0]['start']['dateTime'] + spaceapi_delay < now)102 103 if not open_door_required:104 fail_state = False105 print('Don\'t care (not yet started)')106 delta = events[0]['start']['dateTime'] + spaceapi_delay - now107 sleep = min(config['refresh seconds'], max(0, delta.days*3600*24 + delta.seconds))108 print('Sleeping for {}s until {}'.format(109 sleep, events[0]['start']['dateTime'] + spaceapi_delay))110 time.sleep(sleep)111 continue112 113 open_state = requests.get(config['spaceapi url']).json()['state']['open']114 delta = events[0]['end']['dateTime'] - now115 sleep = min(config['poll seconds'], max(0, delta.days*3600*24 + delta.seconds))116 if not open_state:117 if not fail_state:118 print('OH NOES... we suck... (ongoing open time, but door closed)')119 fail_state = True120 mail('{}\n\n{}'.format(config['fail text'], event_to_string(events[0])))121 else:122 print('still failing :(')123 print('Sleeping for {}s'.format(sleep))124 time.sleep(sleep)125 continue126 else:127 if fail_state:128 print('Opened just now! :) (ongoing open time and door open)')129 fail_state = False130 mail('{}\n\n{}'.format(config['yay text'], event_to_string(events[0])))131 else:132 print('All good :) (ongoing open time and door open)')133 print('Sleeping for {}s'.format(sleep))134 time.sleep(sleep)135 continue136if __name__ == '__main__':137 try:138 main()139 except KeyboardInterrupt:...
PupyTriggers.py
Source:PupyTriggers.py
...16 ON_DISCONNECT: 'on_disconnect',17 ON_DNSCNC_SESSION: 'on_dnscnc_session',18 ON_DNSCNC_SESSION_LOST: 'on_dnscnc_session_lost'19 }.get(event)20def event_to_string(event):21 return {22 ON_START: 'start',23 ON_EXIT: 'exit',24 ON_CONNECT: 'connect',25 ON_DISCONNECT: 'disconnect',26 ON_DNSCNC_SESSION: 'dnscnc session',27 ON_DNSCNC_SESSION_LOST: 'dnscnc session lost'28 }.get(event)29def _do(eventid, action, handler, client_filter):30 event = event_to_string(eventid)31 handler.inject(32 action, client_filter if eventid in (33 ON_CONNECT, ON_DISCONNECT34 ) else None,35 'Action for event "{}" apply to <{}>: {}'.format(36 event, client_filter, action))37def _event(eventid, client, server, handler, config):38 section = event_to_config_section(eventid)39 actions = config.items(section)40 for client_filter, action in actions:41 if client_filter.lower() in ('this', 'self', 'current', '@'):42 if eventid in (ON_CONNECT, ON_DISCONNECT):43 client_filter = client.desc['id']44 else:45 client_filter = client_filter.lower()46 if action.startswith('include:'):47 _, included_section = action.split(':', 1)48 try:49 for nested in config.items(included_section):50 actions.append(nested)51 except NoSectionError:52 pass53 continue54 node = None55 if eventid in (ON_DNSCNC_SESSION, ON_DNSCNC_SESSION_LOST):56 action = action.replace('%c', '{:08x}'.format(client.spi))57 node = '{:012x}'.format(client.system_info['node'])58 elif eventid in (ON_CONNECT, ON_DISCONNECT):59 node = client.desc['node']60 try:61 action = action.format(**client.desc)62 except (ValueError, KeyError) as e:63 logger.error('Invalid action format (%s): %s', action, e)64 criterias = ['*', 'any']65 if node:66 criterias.append(node)67 criterias.extend(list(config.tags(node)))68 if client_filter not in criterias and not client_filter.startswith(('*', 'any')) and \69 (not hasattr(server, 'get_clients') or client_filter not in server.get_clients(client_filter)):70 logger.debug('Incompatible event: eventid=%s criterias=%s client_filter=%s action=%s',71 event_to_string(eventid), criterias, client_filter, action)72 continue73 logger.debug('Compatible event: eventid=%s criterias=%s client_filter=%s action=%s',74 event_to_string(eventid), criterias, client_filter, action)75 _do(eventid, action, handler, client_filter)76def event(eventid, client, server, handler, config):77 try:78 _event(eventid, client, server, handler, config)79 except NoSectionError:80 pass81 except Error, e:82 logger.error(e)83 except Exception, e:...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!