Best Python code snippet using autotest_python
stylish.py
Source:stylish.py
1# This Source Code Form is subject to the terms of the Mozilla Public2# License, v. 2.0. If a copy of the MPL was not distributed with this3# file, You can obtain one at http://mozilla.org/MPL/2.0/.4from __future__ import unicode_literals5from ..result import ResultContainer6try:7 import blessings8except ImportError:9 blessings = None10class NullTerminal(object):11 """Replacement for `blessings.Terminal()` that does no formatting."""12 class NullCallableString(unicode):13 """A dummy callable Unicode stolen from blessings"""14 def __new__(cls):15 new = unicode.__new__(cls, u'')16 return new17 def __call__(self, *args):18 if len(args) != 1 or isinstance(args[0], int):19 return u''20 return args[0]21 def __getattr__(self, attr):22 return self.NullCallableString()23class StylishFormatter(object):24 """Formatter based on the eslint default."""25 # Colors later on in the list are fallbacks in case the terminal26 # doesn't support colors earlier in the list.27 # See http://www.calmar.ws/vim/256-xterm-24bit-rgb-color-chart.html28 _colors = {29 'grey': [247, 8, 7],30 'red': [1],31 'yellow': [3],32 'brightred': [9, 1],33 'brightyellow': [11, 3],34 }35 fmt = " {c1}{lineno}{column} {c2}{level}{normal} {message} {c1}{rule}({linter}){normal}"36 fmt_summary = "{t.bold}{c}\u2716 {problem} ({error}, {warning}){t.normal}"37 def __init__(self, disable_colors=None):38 if disable_colors or not blessings:39 self.term = NullTerminal()40 else:41 self.term = blessings.Terminal()42 self.num_colors = self.term.number_of_colors43 def color(self, color):44 for num in self._colors[color]:45 if num < self.num_colors:46 return self.term.color(num)47 return ''48 def _reset_max(self):49 self.max_lineno = 050 self.max_column = 051 self.max_level = 052 self.max_message = 053 def _update_max(self, err):54 """Calculates the longest length of each token for spacing."""55 self.max_lineno = max(self.max_lineno, len(str(err.lineno)))56 if err.column:57 self.max_column = max(self.max_column, len(str(err.column)))58 self.max_level = max(self.max_level, len(str(err.level)))59 self.max_message = max(self.max_message, len(err.message))60 def _pluralize(self, s, num):61 if num != 1:62 s += 's'63 return str(num) + ' ' + s64 def __call__(self, result):65 message = []66 num_errors = 067 num_warnings = 068 for path, errors in sorted(result.iteritems()):69 self._reset_max()70 message.append(self.term.underline(path))71 # Do a first pass to calculate required padding72 for err in errors:73 assert isinstance(err, ResultContainer)74 self._update_max(err)75 if err.level == 'error':76 num_errors += 177 else:78 num_warnings += 179 for err in errors:80 message.append(self.fmt.format(81 normal=self.term.normal,82 c1=self.color('grey'),83 c2=self.color('red') if err.level == 'error' else self.color('yellow'),84 lineno=str(err.lineno).rjust(self.max_lineno),85 column=(":" + str(err.column).ljust(self.max_column)) if err.column else "",86 level=err.level.ljust(self.max_level),87 message=err.message.ljust(self.max_message),88 rule='{} '.format(err.rule) if err.rule else '',89 linter=err.linter.lower(),90 ))91 message.append('') # newline92 # Print a summary93 message.append(self.fmt_summary.format(94 t=self.term,95 c=self.color('brightred') if num_errors else self.color('brightyellow'),96 problem=self._pluralize('problem', num_errors + num_warnings),97 error=self._pluralize('error', num_errors),98 warning=self._pluralize('warning', num_warnings),99 ))...
tools.py
Source:tools.py
1# -*- coding: utf-8 -*-2"""3:copyright: (c) 2012-2021 by Mike Taylor4:license: CC0 1.0 Universal, see LICENSE for more details.5"""6import os7import logging8import datetime9from urllib.parse import urlparse10def normalizeFilename(filename):11 """Take a given filename and return the normalized version of it.12 Where ~/ is expanded to the full OS specific home directory and all13 relative path elements are resolved.14 """15 return os.path.abspath(os.path.expanduser(filename))16def baseDomain(domain, includeScheme=True):17 """Return only the network location portion of the given domain18 unless includeScheme is True19 """20 result = ''21 url = urlparse(domain)22 if includeScheme:23 if len(url.scheme) > 0:24 result = '%s://' % url.scheme25 if len(url.netloc) == 0:26 result += url.path27 else:28 result += url.netloc29 return result30def pidWrite(pidFile):31 os.umask(0o77) # set umask for pid32 with open(pidFile, "w") as f:33 f.write(str(os.getpid()))34def pidRead(pidFile):35 try:36 with open(pidFile, 'r') as f:37 return int(f.read())38 except IOError:39 return -140def pidClear(pidFile):41 if not isRunning(pidFile):42 if os.path.exists(pidFile):43 os.remove(pidFile)44def isRunning(pidFile):45 pid = pidRead(pidFile)46 if pid == -1:47 return False48 try:49 os.kill(pid, 0)50 return True51 except OSError:52 s = 'pid %d for %s found.' % (pid, pidFile)53 logging.warning(s)54 return False55def _pluralize(template, value):56 s = ''57 if round(value) > 1:58 s = 's'59 return template.format(value, s)60def _zeroDays(seconds, template):61 if seconds < 20:62 return 'just now'63 if seconds < 60:64 return template.format(_pluralize('{:.0f} second{}', seconds))65 if seconds < 120:66 return template.format('a minute')67 if seconds < 3600:68 return template.format(_pluralize('{:.0f} minute{}', seconds / 60))69 if seconds < 7200:70 return template.format('an hour')71 return template.format(_pluralize('{:.0f} hour{}', seconds / 3600))72def relativeDelta(td):73 s = ''74 days = abs(td.days)75 seconds = abs(td.seconds)76 if td.days < 0:77 seconds = 86400 - seconds78 t = "{} ago"79 else:80 t = "in {}"81 if days > 28:82 start = datetime.datetime.now()83 end = start + td84 months = (abs(end.year - start.year) * 12) + (end.month - start.month)85 if days == 0:86 s = _zeroDays(seconds, t)87 else:88 if days == 1:89 if td.days < 0:90 if seconds < 86400:91 s = _zeroDays(seconds, t)92 else:93 s = 'yesterday'94 else:95 s = 'tomorrow'96 elif days < 7:97 s = t.format(_pluralize('{:.0f} day{}', days))98 elif days < 31:99 s = t.format(_pluralize('{:.0f} week{}', days / 7))100 elif days < 365:101 s = t.format(_pluralize('{:.0f} month{}', months))102 else:103 s = t.format(_pluralize('{:.0f} year{}', months / 12))...
polish_timedelta.py
Source:polish_timedelta.py
1# code inspired by https://gist.github.com/n0m4dz/ee41d4ca84e2630e70c62from datetime import timedelta3DAY = {4 'singular': 'dzieÅ',5 'plural1': 'dni',6 'plural2': 'dni'7}8MONTH = {9 'singular': 'miesiÄ
c',10 'plural1': 'miesiÄ
ce',11 'plural2': 'miesiÄcy'12}13YEAR = {14 'singular': 'rok',15 'plural1': 'lata',16 'plural2': 'lat'17}18HOUR = {19 'singular': 'godzina',20 'plural1': 'godziny',21 'plural2': 'godzin'22}23MINUTE = {24 'singular': 'minuta',25 'plural1': 'minuty',26 'plural2': 'minut'27}28SECOND = {29 'singular': 'sekunda',30 'plural1': 'sekundy',31 'plural2': 'sekund'32}33def _pluralize(quantity, dictionary):34 remainder = quantity % 1035 if isinstance(dictionary, dict):36 if 1 < remainder < 5:37 return dictionary['plural1']38 elif quantity == 1:39 return dictionary['singular']40 else:41 return dictionary['plural2']42 else:43 raise TypeError('Nie podano sÅownika')44def localize(timespan):45 if isinstance(timespan, timedelta):46 days = int(timespan.days % 365) % 3047 months = int((timespan.days % 365) / 30)48 years = int(timespan.days / 365)49 hours = int(timespan.seconds / 3600)50 minutes = int(timespan.seconds / 60) % 6051 seconds = timespan.seconds % 6052 days_str = _pluralize(days, DAY)53 months_str = _pluralize(months, MONTH)54 years_str = _pluralize(years, YEAR)55 hours_str = _pluralize(hours, HOUR)56 minutes_str = _pluralize(minutes, MINUTE)57 seconds_str = _pluralize(seconds, SECOND)58 return_string = ""59 if years != 0:60 return_string += "{} {}".format(years, years_str)61 if months != 0:62 return_string += " {} {}".format(months, months_str)63 if days != 0:64 return_string += " {} {}".format(days, days_str)65 if hours != 0:66 return_string += " {} {}".format(hours, hours_str)67 if minutes != 0:68 return_string += " {} {}".format(minutes, minutes_str)69 if seconds != 0:70 return_string += " {} {}".format(seconds, seconds_str)71 return return_string72 else:...
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!!