Best Python code snippet using toolium_python
test_zz_helper.py
Source:test_zz_helper.py  
...25        # startup function is not called, therfore direct print26        print("\n%s - %s: " % ("", cls.__name__))27    def test_check_high23(self):28        helper.config.config_unicode_filename = True29        self.assertEqual(helper.get_valid_filename(u'²³'), u'23')30    def test_check_doubleS(self):31        helper.config.config_unicode_filename = True32        self.assertEqual(helper.get_valid_filename(u'§Ã'), u'SSss')33    def test_check_umlauts(self):34        helper.config.config_unicode_filename = True35        self.assertEqual(helper.get_valid_filename(u'ÃÃÃäöü'), u'AUOaou')36    def test_check_chinese_Characters(self):37        helper.config.config_unicode_filename = True38        self.assertEqual(helper.get_valid_filename(u'æ§ä¸'), u'Zhi Yi')39        helper.config.config_unicode_filename = False40        self.assertEqual(helper.get_valid_filename(u'æ§ä¸'), u'æ§ä¸')41    def test_whitespaces(self):42        helper.config.config_unicode_filename = False43        self.assertEqual(helper.get_valid_filename(u' Alfaman '), u'Alfaman')44    def test_check_finish_Dot(self):45        helper.config.config_unicode_filename = False46        self.assertEqual(helper.get_valid_filename(u'Nameless.'), u'Nameless_')47    def test_check_Limit_Length(self):48        helper.config.config_unicode_filename = False49        self.assertEqual(helper.get_valid_filename(u'1234567890123456789012345678901234567890123456789012345678'50                u'901234567890123456789012345678901234567890123456789012345678901234567890'), u'123456789012345678901'51                u'23456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789'52                u'012345678')53        self.assertEqual(helper.get_valid_filename(u'æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§'54                u'æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§', chars=96),55                         'æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§')56        self.assertEqual(helper.get_valid_filename(u'1æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§'57                u'æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§', chars=96),58                         '1æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§')59        self.assertEqual(helper.get_valid_filename(u'12æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§'60                u'æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§', chars=96),61                         '12æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§æ§')62    def test_check_char_replacement(self):63        helper.config.config_unicode_filename = False64        self.assertEqual(helper.get_valid_filename(u'A*B+C:D"E/F<G>H?'), u'A_B_C_D_E_F_G_H_')65        self.assertEqual(helper.get_valid_filename(u'Alfaman| Name'), u'Alfaman, Name')66        self.assertEqual(helper.get_valid_filename(u'**++** Numi **++**'), u'_ Numi _')67    def test_check_deg_eur_replacement(self):68        helper.config.config_unicode_filename = True69        self.assertEqual(helper.get_valid_filename(u'°â¬'), u'degEUR')70    def test_author_sort(self):71        self.assertEqual(helper.get_sorted_author(u'Hugo Boss'), u'Boss, Hugo')72        self.assertEqual(helper.get_sorted_author(u'Hugo-Peter Boss'), u'Boss, Hugo-Peter')73        self.assertEqual(helper.get_sorted_author(u'Hugo Peter Boss'), u'Boss, Hugo Peter')74        self.assertEqual(helper.get_sorted_author(u'Hugo Boss-Schnuffel'), u'Boss-Schnuffel, Hugo')75    def test_author_sort_roman(self):76        self.assertEqual(helper.get_sorted_author(u'Hügo Böso I'), u'Böso, Hügo I')77        self.assertEqual(helper.get_sorted_author(u'Hügo Böso II.'), u'Böso, Hügo II.')78        self.assertEqual(helper.get_sorted_author(u'Hügo Böso III'), u'Böso, Hügo III')79        self.assertEqual(helper.get_sorted_author(u'Hügo Böso IV.'), u'Böso, Hügo IV.')80    def test_author_sort_junior(self):81        self.assertEqual(helper.get_sorted_author(u'Herb Suli sr.'), u'Suli, Herb sr.')82        self.assertEqual(helper.get_sorted_author(u'Herb Suli jr.'), u'Suli, Herb jr.')83        self.assertEqual(helper.get_sorted_author(u'Herb Suli jr'), u'Suli, Herb jr')...cache_manager.py
Source:cache_manager.py  
...32    else:33        cached_result = pipe.get(key)34        return cached_result35# https://github.com/django/django/blob/master/django/utils/text.py#L21936def get_valid_filename(s):37    s = str(s).strip().replace(" ", "_")38    s = str(s).lstrip("/").replace("/", "_")39    return re.sub(r"(?u)[^-\w.]", "", s)40def cache_frame(frame, duration=DEFAULT_CACHE_TIME):41    # Check that we aren't doing this recursively...42    parent_parent_frame = inspect.getouterframes(frame)[1][0]43    _, _, parent_parent_fn_name, _, _ = inspect.getframeinfo(parent_parent_frame)44    if parent_parent_fn_name == cache_frame.__name__:45        return None, None46    # Get the original function and what was passed to it in order to call it47    _, _, _, vals = inspect.getargvalues(frame)48    filename, _, fn_name, _, _ = inspect.getframeinfo(frame)49    orig_frame = inspect.getouterframes(frame)[0][0]50    orig_fn = orig_frame.f_globals[fn_name]51    filename_str = get_valid_filename(filename)52    fn_name_str = get_valid_filename(fn_name)53    vals_str = get_valid_filename(str(vals))54    key = f"{filename_str}::{fn_name_str}({vals_str})"55    # cached_result = redis.get(key)56    cached_result = retrieve(key)57    # if theres a cache hit, return it58    if cached_result is not None:59        logger.debug(f"Returning cache for {key} ({cached_result})")60        return cached_result, True61    # if not, store it in the cache62    result = orig_fn(**vals)63    # redis.set(key, zlib.compress(json.dumps(result)))64    store(key, result)65    return result, False66def purge_frame_cache(fn, *args, **kwargs):67    fn_name = get_valid_filename(fn.__name__)68    filename_str = get_valid_filename(inspect.getsourcefile(fn))69    vals_str = get_valid_filename(str(kwargs))70    redis.delete(f"{filename_str}::{fn_name}({vals_str})")71def call(fn, refresh=False, pipe=None, *args, **kwargs):72    fn_str = get_valid_filename(fn.__name__)73    args_str = get_valid_filename(str(args))74    kwargs_str = get_valid_filename(str(kwargs))75    key = f"{fn_str}({args_str}_{kwargs_str})"76    # cached_result = redis.get(key)77    cached_result = retrieve(key, pipe=pipe)78    if cached_result is not None and not refresh:79        # cached_result = json.loads(zlib.decompress(cached_result))80        return cached_result81    # noinspection PyArgumentList82    result = fn(*args, **kwargs)83    if isinstance(result, tbapy.models._base_model_class):84        result = dict(result)85    # redis.set(key, zlib.compress(json.dumps(result)))86    store(key, result, pipe=pipe)87    return result88def batch_call(iterable, fn, get_args, get_kwargs):89    with redis.pipeline() as pipe:90        keys = []91        for x in iterable:92            args = get_args(x)93            kwargs = get_kwargs(x)94            fn_str = get_valid_filename(fn.__name__)95            args_str = get_valid_filename(str(args))96            kwargs_str = get_valid_filename(str(kwargs))97            key = f"{fn_str}({args_str}_{kwargs_str})"98            keys.append(key)99        for key in keys:100            retrieve(key, pipe=pipe)101        res1 = pipe.execute()102        results = {}103        for key, res in zip(keys, res1):104            if res is not None:105                res = postprocess(res)106            results[key] = res107        for x in iterable:108            args = get_args(x)109            kwargs = get_kwargs(x)110            fn_str = get_valid_filename(fn.__name__)111            args_str = get_valid_filename(str(args))112            kwargs_str = get_valid_filename(str(kwargs))113            key = f"{fn_str}({args_str}_{kwargs_str})"114            if results[key] is None:115                logger.debug(f"Calling {fn}({args}, {kwargs})")116                results[key] = call(fn, *args, **kwargs, pipe=pipe)117        pipe.execute()...main.py
Source:main.py  
...9import praw10from keep_alive import keep_alive11intents = discord.Intents.all()12client = commands.Bot(command_prefix = '.', intents = intents)13def get_valid_filename(s):14    ''' strips out special characters and replaces spaces with underscores, len 200 to avoid file_name_too_long error '''15    s = str(s).strip().replace(' ', '_')16    return re.sub(r'[^\w.]', '', s)[:200]17def erase_previous_line():18    # cursor up one line19    sys.stdout.write("\033[F")20    # clear to the end of the line21    sys.stdout.write("\033[K")22def get_pictures_from_subreddit(data, subreddit, location, nsfw):23    for i in range(len(data)):24        if data[i]['data']['over_18']:25            # if nsfw post and you only want sfw26            if nsfw == 'n':27                continue28        else:29            # if sfw post and you only want nsfw30            if nsfw == 'x':31                continue32        current_post = data[i]['data']33        image_url = current_post['url']34        if '.png' in image_url:35            extension = '.png'36        elif '.jpg' in image_url or '.jpeg' in image_url:37            extension = '.jpeg'38        elif 'imgur' in image_url:39            image_url += '.jpeg'40            extension = '.jpeg'41        else:42            continue43        erase_previous_line()44        print('downloading pictures from r/' + subreddit +45              '.. ' + str((i*100)//len(data)) + '%')46        # redirects = False prevents thumbnails denoting removed images from getting in47        image = requests.get(image_url, allow_redirects=False)48        if(image.status_code == 200):49            try:50                if os.path.exists(location + '' + get_valid_filename(current_post['title']) + extension):51                    return get_valid_filename(current_post['title']) + extension52                53                else: 54                    output_filehandle = open(55                    location + '' + get_valid_filename(current_post['title']) + extension, mode='bx')56                    output_filehandle.write(image.content)57                    return get_valid_filename(current_post['title']) + extension58            except:59                pass60        61@client.event62async def on_ready():63  print('We have logged in as {0.user}'.format(client))64@client.event65async def on_member_join(member):66    channel = client.get_channel(806975695695380510)67    await channel.send(f'{member} Vantiya neel ku. Ivanum nasama poga poran.')68  69@client.command()70async def ping(ctx):71  await ctx.send(f'{round(client.latency * 1000)} ms')...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!!
