Skip to content

Sourcery Starbot ⭐ refactored RumiAllbert/wttr.in#3

Open
SourceryAI wants to merge 1 commit into
RumiAllbert:masterfrom
SourceryAI:master
Open

Sourcery Starbot ⭐ refactored RumiAllbert/wttr.in#3
SourceryAI wants to merge 1 commit into
RumiAllbert:masterfrom
SourceryAI:master

Conversation

@SourceryAI

Copy link
Copy Markdown

Thanks for starring sourcery-ai/sourcery ✨ 🌟 ✨

Here's your pull request refactoring your most popular Python repo.

If you want Sourcery to refactor all your Python repos and incoming pull requests install our bot.

Review changes via command line

To manually merge these changes, make sure you're on the master branch, then run:

git fetch https://github.com/sourcery-ai-bot/wttr.in master
git merge --ff-only FETCH_HEAD
git reset HEAD^

@SourceryAI SourceryAI left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Due to GitHub API limits, only the first 60 comments can be shown.

Comment thread bin/geo-proxy.py
Comment on lines -91 to +95
print("cache found: %s" % location)
print(f"cache found: {location}")

if answer is None:
answer = query_osm(location)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function find_location refactored with the following changes:

Comment thread bin/proxy.py
but is using the fake data from "test/proxy-data".

"""

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 37-37 refactored with the following changes:

Comment thread bin/proxy.py
Comment on lines -56 to +57
f_name = 'share/translations/%s.txt' % f_name
f_name = f'share/translations/{f_name}.txt'

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function load_translations refactored with the following changes:

Comment thread bin/proxy.py
Comment on lines -91 to +97
digest = hashlib.sha1(("%s %s" % (path, query)).encode("utf-8")).hexdigest()
digest = hashlib.sha1(f"{path} {query}".encode("utf-8")).hexdigest()
digest_number = ord(digest[0].upper())
expiry_interval = 60*(digest_number+90)

timestamp = "%010d" % (int(time.time())//expiry_interval*expiry_interval)
filename = os.path.join(PROXY_CACHEDIR, timestamp, path, query)

return filename
return os.path.join(PROXY_CACHEDIR, timestamp, path, query)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _cache_file refactored with the following changes:

Comment thread bin/proxy.py
Comment on lines -107 to +108
return (open(cache_file, 'r').read(),
json.loads(open(cache_file+".headers", 'r').read()))
return open(cache_file, 'r').read(), json.loads(
open(f"{cache_file}.headers", 'r').read()
)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _load_content_and_headers refactored with the following changes:

Comment thread lib/globals.py
Comment on lines -148 to +149
help_file = os.path.join(MYDIR, 'share/translations/%s-help.txt' % lang)
if os.path.exists(help_file):
return help_file
return HELP_FILE
help_file = os.path.join(MYDIR, f'share/translations/{lang}-help.txt')
return help_file if os.path.exists(help_file) else HELP_FILE

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_help_file refactored with the following changes:

Comment thread lib/limits.py
Comment on lines -46 to +47
if limits:
self.limit = _time_caps(*limits)
else:
self.limit = _time_caps(30, 600, 1000)

if whitelist:
self.whitelist = whitelist[:]
else:
self.whitelist = []

self.limit = _time_caps(*limits) if limits else _time_caps(30, 600, 1000)
self.whitelist = whitelist[:] if whitelist else []

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Limits.__init__ refactored with the following changes:

Comment thread lib/limits.py
Comment on lines -78 to +70
log("%s LIMITED [%s for %s]" % (ip_address, self._get_limit(interval), interval))
log(f"{ip_address} LIMITED [{self._get_limit(interval)} for {interval}]")

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Limits._report_excessive_visits refactored with the following changes:

Comment thread lib/limits.py
Comment on lines -92 to +84
return ("Not so fast! Number of queries per %s is limited to %s"
% (interval, self._get_limit(interval)))
return f"Not so fast! Number of queries per {interval} is limited to {self._get_limit(interval)}"

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Limits.check_ip refactored with the following changes:

Comment thread lib/location.py
Comment on lines -102 to +113
geo = requests.get('%s/%s' % (GEOLOCATOR_SERVICE, location)).text
geo = requests.get(f'{GEOLOCATOR_SERVICE}/{location}').text
except requests.exceptions.ConnectionError as exception:
print("ERROR: %s" % exception)
print(f"ERROR: {exception}")
return None

if geo == "":
return None

try:
answer = json.loads(geo.encode('utf-8'))
return answer
return json.loads(geo.encode('utf-8'))
except ValueError as exception:
print("ERROR: %s" % exception)
print(f"ERROR: {exception}")

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _geolocator refactored with the following changes:

Comment thread lib/location.py
Comment on lines -137 to +136
file.write(location[3] + ';' + location[2] + ';' + location[1] + ';' + location[0])
file.write(f'{location[3]};{location[2]};{location[1]};{location[0]}')

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _ipcachewrite refactored with the following changes:

Comment thread lib/location.py
Comment on lines -158 to +157
_debug_log("[_ipcache] %s not found" % ip_addr)
_debug_log(f"[_ipcache] {ip_addr} not found")

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _ipcache refactored with the following changes:

Comment thread lib/location.py
Comment on lines -176 to +185
_debug_log("[_ip2location] %s search" % ip_addr)
_debug_log(f"[_ip2location] {ip_addr} search")
r = requests.get(
'http://api.ip2location.com/?ip=%s&key=%s&package=WS3' # WS5 provides latlong
% (ip_addr, IP2LOCATION_KEY))
f'http://api.ip2location.com/?ip={ip_addr}&key={IP2LOCATION_KEY}&package=WS3'
)
r.raise_for_status()
location = r.text

parts = location.split(';')
if len(parts) >= 4:
# ccode, country, region, city, (rest)
_debug_log("[_ip2location] %s found" % ip_addr)
_debug_log(f"[_ip2location] {ip_addr} found")

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _ip2location refactored with the following changes:

This removes the following comments ( why? ):

# WS5 provides latlong

Comment thread lib/location.py
Comment on lines -197 to +196
r = requests.get(
'https://ipinfo.io/%s/json?token=%s'
% (ip_addr, IPINFO_TOKEN))
r = requests.get(f'https://ipinfo.io/{ip_addr}/json?token={IPINFO_TOKEN}')

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _ipinfo refactored with the following changes:

Comment thread lib/location.py
Comment on lines -215 to +216
_debug_log("[_geoip] %s search" % ip_addr)
_debug_log(f"[_geoip] {ip_addr} search")
response = GEOIP_READER.city(ip_addr)
# print(response.subdivisions)
city, region, country, ccode, lat, long = response.city.name, response.subdivisions[0].names["en"], response.country.name, response.country.iso_code, response.location.latitude, response.location.longitude
_debug_log("[_geoip] %s found" % ip_addr)
_debug_log(f"[_geoip] {ip_addr} found")

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _geoip refactored with the following changes:

Comment thread lib/metno.py
Comment on lines -359 to +360
converted_hours = []
for hour in hours:
converted_hours.append(_convert_hour(hour))
return converted_hours
return [_convert_hour(hour) for hour in hours]

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _convert_hourly refactored with the following changes:

Comment thread lib/parse_query.py
Comment on lines +51 to +56
elif us_ip:
query['use_imperial'] = True
query['use_metric'] = False
else:
if us_ip:
query['use_imperial'] = True
query['use_metric'] = False
else:
query['use_imperial'] = False
query['use_metric'] = True
query['use_imperial'] = False
query['use_metric'] = True

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function metric_or_imperial refactored with the following changes:

Comment thread lib/parse_query.py
Comment on lines -166 to +165
parsed.update(parse_query(to_be_parsed))
parsed |= parse_query(to_be_parsed)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function parse_wttrin_png_name refactored with the following changes:

Comment thread lib/weather_data.py
'?key=%s&q=%s&format=json'
'&num_of_days=3&tp=3&lang=%s') % (key, location, lang)
url = 'http://127.0.0.1:5001' + url
url = f'http://127.0.0.1:5001{url}'

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_weather_data refactored with the following changes:

Comment thread lib/wttr_srv.py
user_agent = parsed_query.get("user_agent", "").lower()
html_output = not any(agent in user_agent for agent in PLAIN_TEXT_AGENTS)
return html_output
return all(agent not in user_agent for agent in PLAIN_TEXT_AGENTS)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_output_format refactored with the following changes:

Comment thread lib/wttr_srv.py
Comment on lines -232 to +240
else:
if query.get('days', '3') != '0' \
elif query.get('days', '3') != '0' \
and not query.get('no-follow-line') \
and ((parsed_query.get("view") or "v2")[:2] in ["v2", "v3"]):
if parsed_query['html_output']:
output = add_buttons(output)
else:
message = get_message('FOLLOW_ME', parsed_query['lang'])
if parsed_query.get('no-terminal', False):
message = remove_ansi(message)
output += '\n' + message + '\n'
if parsed_query['html_output']:
output = add_buttons(output)
else:
message = get_message('FOLLOW_ME', parsed_query['lang'])
if parsed_query.get('no-terminal', False):
message = remove_ansi(message)
output += '\n' + message + '\n'

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _response refactored with the following changes:

Comment thread lib/wttr_srv.py
Comment on lines -291 to +289
parsed_query.update(parse_query.parse_wttrin_png_name(png_filename))
parsed_query |= parse_query.parse_wttrin_png_name(png_filename)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function parse_request refactored with the following changes:

Comment thread lib/fmt/png.py
Comment on lines -95 to +99
if inverse:
return 'black'
return 'lightgray'

return 'black' if inverse else 'lightgray'
if color in ['green', 'black', 'cyan', 'blue', 'brown']:
return color
try:
return (
int(color[0:2], 16),
int(color[2:4], 16),
int(color[4:6], 16))
return int(color[:2], 16), int(color[2:4], 16), int(color[4:6], 16)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _color_mapping refactored with the following changes:

Comment thread lib/fmt/png.py
Comment on lines -157 to +151
if cat in ['Latin', 'Common']:
return 'default'
return cat
return 'default' if cat in ['Latin', 'Common'] else cat

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _script_category refactored with the following changes:

Comment thread lib/fmt/png.py
Comment on lines -198 to +190
font = {}
for cat in FONT_CAT:
font[cat] = ImageFont.truetype(FONT_CAT[cat], FONT_SIZE)

font = {cat: ImageFont.truetype(FONT_CAT[cat], FONT_SIZE) for cat in FONT_CAT}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _gen_term refactored with the following changes:

Comment thread lib/view/line.py
Comment on lines -381 to +378
return 'Unknown location; please try ~%s' % parsed_query["location"]
return f'Unknown location; please try ~{parsed_query["location"]}'

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function format_weather_data refactored with the following changes:

Comment thread lib/view/line.py
Comment on lines -416 to +413
output = format_weather_data(query, parsed_query, data)
return output
return format_weather_data(query, parsed_query, data)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function wttr_line refactored with the following changes:

Comment thread lib/view/moon.py
dateutil.parser.parse(date)
except Exception as e:
print("ERROR: %s" % e)
print(f"ERROR: {e}")

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_moon refactored with the following changes:

Comment thread lib/view/prometheus.py
Comment on lines -68 to +69
data["weather"][i], for_day="%sd" % i, already_seen=already_seen)
data["weather"][i], for_day=f"{i}d", already_seen=already_seen
)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function render_prometheus refactored with the following changes:

Comment thread lib/view/v2.py
Comment on lines -58 to +60
url = (
'http://'
'localhost:5001/premium/v1/weather.ashx'
'?key=%s'
'&q=%s&format=json&num_of_days=3&tp=3&lang=None'
) % (WWO_KEY, config["location"])
url = f'http://localhost:5001/premium/v1/weather.ashx?key={WWO_KEY}&q={config["location"]}&format=json&num_of_days=3&tp=3&lang=None'
text = requests.get(url).text
parsed_data = json.loads(text)
return parsed_data
return json.loads(text)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_data refactored with the following changes:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant