Best Python code snippet using tempest_python
reddit_scraper.py
Source:reddit_scraper.py  
1import discord2import mimetypes3import requests4import random56from io import BytesIO7from utils import permissions, http8from discord.ext.commands import errors91011class RedditPost:12    """13    Represents a single reddit post with the following attributes:141516    (str) subreddit: the subreddit that the post belongs to17    (str) title: the title of the post18    (str) author: the author of the post19    (str) url: link to the image within the reddit post20    (bool) nsfw: whether or not the post is flagged for NSFW content21    (int) upvotes: the number of upvotes22    """23    def __init__(self, subreddit, title, author, url, nsfw, upvotes):24        self.subreddit = subreddit25        self.title = title26        self.author = author27        self.url = url28        self.nsfw = nsfw29        self.upvotes = upvotes3031    def get_subreddit(self):32        return self.subreddit3334    def get_title(self):35        return self.title3637    def get_author(self):38        return self.author3940    def get_url(self):41        return self.url4243    def get_nsfw(self):44        return self.nsfw4546    def get_upvotes(self):47        return self.upvotes4849    def __str__(self):50        return '%s %s %s %s %s %d' % (51            self.subreddit,52            self.title,53            self.author,54            self.url,55            self.nsfw,56            self.upvotes,57        )585960def _get_rand_post(json_url):61    """Parses the JSON data and returns a RedditPost object corresponding to a random post."""6263    all_post_data = requests.get(url=json_url,64                                headers={'user-agent': 'created by Paigekins'}65                                ).json()['data']['children']6667    if all_post_data is None:68        raise ValueError('No posts in subreddit.')6970    finding_post = True71    while finding_post:72        try:73            rand_post = all_post_data[random.choice([74                i for i in range(len(all_post_data))75            ])]['data']7677            post_obj = RedditPost(78                rand_post['subreddit'],79                rand_post['title'],80                rand_post['author'],81                rand_post['url'],82                rand_post['over_18'],83                rand_post['ups']84            )8586            finding_post = False8788            return post_obj8990        except KeyError:91            print('Post could not be parsed. Finding another...')9293def _is_image(url):94    """95    Checks whether a normal url contains an image.9697    Params:98        (str) url: the url for the image99    Returns:100        (bool): True if url contains an image, False otherwise.101    """102    mimetype, encoding = mimetypes.guess_type(url)103    return (mimetype and mimetype.startswith('image'))104105106def _is_gif(url):107    """Checks if the url contains a gif (not implemented yet)"""108    content_type = requests.head(url).headers['Content-Type']109    pass110111112def most_upvoted(all_post_data):113    """114    Finds the most upvoted post from some data containing posts (not implemented).115116    Params:117        (dict) all_post_data: data on one or more posts118    Returns:119        (dict): data on the most highly upvoted post120    """121    pass122123124async def _create_embed(ctx, post: RedditPost):125    """Creates a tuple with the embed and the chosen random image url"""126    try:127        author = ctx.message.author128        rand_url = post.get_url()129        embed = discord.Embed(130            title=post.get_title() if len(post.get_title()) < 256 else 'Title too long to display ;A;',131            description='**OP**: ' + '/u/' + post.get_author() + f'\n **Updoots**: {str(post.get_upvotes())} \n',132            url=post.get_url(),133            colour=ctx.me.top_role.colour,134        )135        embed.set_footer(text=f'Requested by {author.name}, and retrieved from /r/ {post.get_subreddit()}.')136        return embed, rand_url137138    except AttributeError:139        raise AttributeError('Post parameter must be a RedditPost object.')140141142async def reddit_imgscrape(ctx, url):143    """144    Randomly selects an image from a subreddit corresponding to a json url and sends it to the channel.145    Checks for permissions, NSFW-mode.146147    Params:148        (commands.Context): context149        (str): json url150    """151    current_channel = ctx.message.channel152    author = ctx.message.author153    154    try:155        await ctx.trigger_typing()156157        rand_post = _get_rand_post(url) # RedditPost object158159        embed, rand_url = await _create_embed(ctx, rand_post)160161        if not permissions.can_attach(ctx):162            await current_channel.send('I cannot upload images/GIFs here ;w;')163164        elif not permissions.is_nsfw(ctx) and rand_post.get_nsfw():165            await current_channel.send(f'L-lewd {author.name}! NSFW commands go in NSFW channels!! >///<')166167        else:168            try:169                if _is_image(rand_url):170                    bio = BytesIO(await http.get(rand_url, res_method='read'))171                    extension = rand_url.split('.')[-1]172                    await current_channel.send(embed=embed)173                    await current_channel.send(file=discord.File(bio, filename=f'image.{extension}'))174                else:175                    await current_channel.send(embed=embed)176                    await current_channel.send(rand_url)177178            except KeyError:179                await current_channel.send('That didn\'t work ;o; please try the command again.')180    except:
...main.py
Source:main.py  
1import mysql.connector2import hashlib3map = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"4#function to convert id to short url using map we define with base 625def idToShortURL(id):6    shortURL = ""7    if id == 0 :8        return "a"9    # for each digit find the base 6210    while (id > 0):11        shortURL += map[id % 62]12        id //= 6213    return shortURL[::-1]14#function to convert url to id by using algorithm until we move all over the characters till get the id15def URLToId(shortURL):16    id = 017    for i in shortURL:18        val_i = ord(i)19        if (val_i >= ord('a') and val_i <= ord('z')):20            id = id * 62 + val_i - ord('a')21        elif (val_i >= ord('A') and val_i <= ord('Z')):22            id = id * 62 + val_i - ord('A') + 2623        else:24            id = id * 62 + val_i - ord('0') + 5225    return id26#function to handle all over the connection in data base27def ConnectToDB():28    try:29        connection=mysql.connector.connect(30            host="b39pjqvxy6ddkgcf5qwu-mysql.services.clever-cloud.com",31            user="uecz3fzsqf8nap2g",32            password="0E0c7SI3aemdP0iZdryd",33            database="b39pjqvxy6ddkgcf5qwu")34    except mysql.connector.Error as error:35        print("Failed to insert record into Laptop table {}".format(error))36    return connection37def CheckIdinDB(connection,id):38    cursor = connection.cursor()39    sql_select_query = """select * from websites where id = %s"""40    # set variable in query41    cursor.execute(sql_select_query, (id,))42    # fetch result43    record = cursor.fetchall()44    if len(record)==0:45        return False46    return record47def SaveIdinDB(connection,id):48    cursor = connection.cursor()49    mySql_insert_query = "INSERT INTO websites (id,originalURL,shortURL) VALUES (%s,%s, %s)"50    shortURL=idToShortURL(int(id))51    val = (str(id), URL,"http://"+shortURL+".com")52    cursor.execute(mySql_insert_query, val)53    connection.commit()54    print(cursor.rowcount, "Record inserted successfully into Laptop table")55    cursor.close()56    return shortURL57#two options to convert that user can choose betweem two cases58def LongURLToShort(URL):59    connection=ConnectToDB()60    id=str(hash(URL))[1:13]61    result=CheckIdinDB(connection,id)62    print(result)63    if result==False:64        shortURL=SaveIdinDB(connection,id)65    else:66        shortURL=result[0][2]67    if connection.is_connected():68        connection.close()69        print("MySQL connection is closed")70    return "http://"+shortURL+".com"71def sanity_check(loops=1):72    import random73    import cowsay74    rand_url = ""75    for i in range(loops):76        for char in range(random.randint(1, 10)):77            rand_url += random.choice(map)78        #rand_url = "1"79        print("generated URL is {0}".format(rand_url))80        expected_id = URLToId(rand_url)81        print("expected id is {0}".format(expected_id))82        actual_url = idToShortURL(expected_id)83        print("actual is {0}".format(actual_url))84        if rand_url != actual_url:85            cowsay.daemon("fail !!!! check following URL {0}, id is {1} , actual URL is {2}".format(rand_url, expected_id, actual_url))86        else:87            cowsay.daemon("passed!! {0} == {1}".format(rand_url, actual_url))88Descision=input("To short URL: Click 1\nTo reach for existing URL Click 2\n")89URL=input("Please Enter your URL: ")90if len(URL)>500:91    print("Your URL is length is out of range")92    exit(1)93if URL[0:7]!="http://":94    print("URL must start with http://")95    exit(1)96if Descision=='1':97   print("Your Short URL is: "+LongURLToShort(URL))98elif Descision=='2':99    connection = ConnectToDB()100    result = CheckIdinDB(connection, URLToId(URL[7:len(URL)-4]))101    if result == False:102        print("404: Page not found")103    else:104        print("You have reached to page: " + result[0][0])105    if connection.is_connected():106        connection.close()107        print("MySQL connection is closed")108#In case you want to see the test cases you can run the sanity check below:...prntsc_disc.py
Source:prntsc_disc.py  
1from urllib.request import Request, urlopen2from bs4 import BeautifulSoup3import random, string, json,discord4x = 05string = "abcdefjhijklmnopqrstuvwrxyz0123456789"6def randurl():7    a = random.choice(string.lower())8    b = random.choice(string.lower())9    c = random.choice(string.lower())10    d = random.choice(string.lower())11    e = random.choice(string.lower())12    f = random.choice(string.lower())13    rand_url = str(a) + str(b) + str(c) + str(d) + str(e) + str(f)14    return rand_url15def getimage():16    x = False17    while x == False:18        rand_url = randurl()19        req = Request('https://prnt.sc/' + rand_url, headers={'User-Agent': 'Mozilla/5.0'})20        webpage = urlopen(req).read()21        soup = BeautifulSoup(webpage, 'html.parser')22        name_box = soup.find(id="screenshot-image")23        try:24            Request(name_box.get('src'), headers={'User-Agent': 'Mozilla/5.0'})25        except (AttributeError, ValueError):26            x = False27        else:28            x = True29            embed = discord.Embed(title = rand_url, url = "https://prnt.sc/" + rand_url, colour = 0xFF00CC)30            embed.set_image(url = name_box.get('src'))...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!!
