Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sourcery Starbot ⭐ refactored akkana/scripts #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 4 additions & 10 deletions analemma.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,19 +40,13 @@ def __init__(self, observer, year, lunar=False, background=None):
self.width = 0
self.height = 0
# Even if we're actually showing the moon, call the object self.sun.
if self.lunar:
self.sun = ephem.Moon()
else:
self.sun = ephem.Sun()
self.sun = ephem.Moon() if self.lunar else ephem.Sun()
self.sinusoidal = False

self.sun_color = (1, 1, 0)
self.backside_color = (1, .7, 0)
self.text_color = (1, 1, 0)
if background:
self.background_color = background
else:
self.background_color = (0, 0, .6, 1)
self.background_color = background if background else (0, 0, .6, 1)
Comment on lines -43 to +49
Copy link
Author

Choose a reason for hiding this comment

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

Function AnalemmaWindow.__init__ refactored with the following changes:

  • Replace if statement with if expression

self.special_dot_size = 5

def draw_sun_position(self, date):
Expand Down Expand Up @@ -398,7 +392,7 @@ def draw(self, widget, ctx, background=None, labels=True):
ctx.set_source_rgba(*background)
if self.sinusoidal:
self.draw_rectangle(0, 0, self.width, self.height)
for f in range(0, int(math.pi * 100)):
for f in range(int(math.pi * 100)):
Comment on lines -401 to +395
Copy link
Author

Choose a reason for hiding this comment

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

Function AnalemmaWindow.draw refactored with the following changes:

  • Replace range(0, x) with range(x)
  • Replace unused for index with underscore

theta = f/200.
(x, y) = self.project_sinusoidal(math.pi/2, theta)
self.draw_rectangle(x, y, self.width - 2*x, 4)
Expand Down Expand Up @@ -431,7 +425,7 @@ def draw(self, widget, ctx, background=None, labels=True):

# For testing, try replacing 30 with, say, 5000 to see the
# motion of the moon over many years.
for i in range(0, 30):
for _ in range(30):
self.draw_sun_position(transit)

# Also draw lunar analemmas 4 hours earlier and later:
Expand Down
17 changes: 6 additions & 11 deletions androidfiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,9 @@ def list_local_dir(path, sorted=True, sizes=False, recursive=False):
like foo/bar/baz.jpg.
"""
path = os.path.normpath(path)
lenpath = len(path)
if recursive:
file_list = []
lenpath = len(path)
Comment on lines -151 to +153
Copy link
Author

Choose a reason for hiding this comment

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

Function list_local_dir refactored with the following changes:

  • Move assignments closer to their usage

for root, dirs, files in os.walk(path):
root = os.path.normpath(root)
for f in files:
Expand Down Expand Up @@ -244,7 +244,7 @@ def copyfile(src, dst, move=False):
doesn't create directories first.
If move=True, use move rather than copy (remove the src).
"""
if not is_android(src) and not is_android(dst):
if not (is_android(src) or is_android(dst)):
Copy link
Author

Choose a reason for hiding this comment

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

Function copyfile refactored with the following changes:

  • Simplify logical expression

if move:
shutil.move(src, dst)
else:
Expand Down Expand Up @@ -299,10 +299,9 @@ def find_basename_size_match(pair, pairlist):
match = None
num_matches = 0
for i, p in enumerate(pairlist):
if os.path.basename(p[0]) == base:
if p[1] == pair[1]:
match = i
num_matches += 1
if os.path.basename(p[0]) == base and p[1] == pair[1]:
match = i
num_matches += 1
Comment on lines -302 to +304
Copy link
Author

Choose a reason for hiding this comment

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

Function find_basename_size_match refactored with the following changes:

  • Merge nested if conditions

if num_matches == 1:
return match
elif num_matches > 1:
Expand Down Expand Up @@ -464,11 +463,7 @@ def find_dir_in(thedir, whichlist):
# match books whose titles start with the same name as the dir.
if not thedir.endswith('/'):
thedir += '/'
for pair in whichlist:
if pair[0].startswith(thedir):
return True

return False
return any(pair[0].startswith(thedir) for pair in whichlist)
Comment on lines -467 to +466
Copy link
Author

Choose a reason for hiding this comment

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

Function sync.find_dir_in refactored with the following changes:

  • Use any() instead of for loop


def remember_needed_dirs(f):
"""Check full pathname f (from src_ls) to see if its dirname
Expand Down
22 changes: 11 additions & 11 deletions bdump
Original file line number Diff line number Diff line change
Expand Up @@ -22,26 +22,26 @@ def Usage() :
print("Usage: %s [-cxd] file ..." % os.path.basename(sys.argv[0]))
exit(1)

def parse_opts() :
def parse_opts():
global do_char, do_hex, do_dec, file_list, multi_format
num_formats = 0
for i in range(1, len(sys.argv)) :
for i in range(1, len(sys.argv)):
if sys.argv[i][0] != '-' :
file_list = sys.argv[i:]
break
for c in sys.argv[i][1:] :
if c == 'c' :
for c in sys.argv[i][1:]:
if c == 'c':
do_char = True
num_formats = num_formats + 1
elif c == 'x' :
do_hex = True
num_formats = num_formats + 1
elif c == 'd' :
num_formats += 1
elif c == 'd':
do_dec = True
num_formats = num_formats + 1
elif c == 'h' :
num_formats += 1
elif c == 'h':
Usage()

elif c == 'x':
do_hex = True
num_formats += 1
Comment on lines -25 to +44
Copy link
Author

Choose a reason for hiding this comment

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

Function parse_opts refactored with the following changes:

  • Simplify conditional into switch-like form
  • Replace assignment with augmented assignment

if num_formats == 0 :
do_char = True
do_hex = True
Expand Down
17 changes: 3 additions & 14 deletions birdcodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,7 @@ def __init__(self):
fields = next(reader)
code4 = fields.index('4code')
name = fields.index('name')
if 'sci_name' in fields:
sciname = fields.index('sci_name')
else:
sciname = None

sciname = fields.index('sci_name') if 'sci_name' in fields else None
Copy link
Author

Choose a reason for hiding this comment

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

Function BirdCodes.__init__ refactored with the following changes:

  • Replace if statement with if expression

for fields in reader:
if sciname:
self.allbirds[fields[code4]] = (fields[name], fields[sciname])
Expand All @@ -53,11 +49,7 @@ def __init__(self):
fields = next(reader)
code4 = fields.index('4code')
name = fields.index('name')
if 'sci_name' in fields:
sciname = fields.index('sci_name')
else:
sciname = None

sciname = fields.index('sci_name') if 'sci_name' in fields else None
for fields in reader:
if fields[code4] in self.allbirds:
continue
Expand All @@ -83,10 +75,7 @@ def match_code(self, matchcode):
return None

def match_codes(self, matchcodes):
matches = []
for code in matchcode:
matches.append(self.match_code(code))
return matches
return [self.match_code(code) for code in matchcode]
Comment on lines -86 to +78
Copy link
Author

Choose a reason for hiding this comment

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

Function BirdCodes.match_codes refactored with the following changes:

  • Convert for loop into list comprehension
  • Inline variable that is only used once


def match_name(self, matchname, fuzzy=True):
matchname = matchname.upper()
Expand Down
15 changes: 7 additions & 8 deletions cachefile.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ def time_bounds(self, starttime=None, endtime=None, day=None, now=None):
starttime = self.day_start(day)
endtime = self.day_end(day)

elif not starttime and not endtime:
elif not (starttime or endtime):
Copy link
Author

Choose a reason for hiding this comment

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

Function Cachefile.time_bounds refactored with the following changes:

  • Simplify logical expression

# Set back to the beginning of the day:
starttime = self.day_start(now)
# and end now.
Expand All @@ -235,9 +235,11 @@ def time_bounds(self, starttime=None, endtime=None, day=None, now=None):
# Else end at the end of the day we started:
else:
endtime = self.day_end(starttime)
elif starttime.year != endtime.year \
or starttime.month != endtime.month \
or starttime.day != endtime.day:
elif not (
starttime.year == endtime.year
and starttime.month == endtime.month
and starttime.day == endtime.day
):
raise ValueError("time_bounds: %s and %s must start and end on the same day" % (endtime, starttime))

if starttime > endtime:
Expand All @@ -260,10 +262,7 @@ def get_data(self, starttime=None, endtime=None):
data = []

if not endtime:
if starttime:
endtime = self.day_start(starttime)
else:
endtime = datetime.datetime.now()
endtime = self.day_start(starttime) if starttime else datetime.datetime.now()
Comment on lines -263 to +265
Copy link
Author

Choose a reason for hiding this comment

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

Function Cachefile.get_data refactored with the following changes:

  • Swap positions of nested conditionals
  • Hoist repeated code outside conditional statement
  • Replace if statement with if expression

if not starttime:
starttime = self.day_start(endtime)

Expand Down
19 changes: 8 additions & 11 deletions cellaut.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,7 @@ def __repr__(self):
out = ''
for row in self.grid:
for cell in row:
if self.characters:
out += self.characters[cell]
else:
out += '%3d' % cell
out += self.characters[cell] if self.characters else '%3d' % cell
Copy link
Author

Choose a reason for hiding this comment

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

Function Cellgrid.__repr__ refactored with the following changes:

  • Replace if statement with if expression

out += '\n'
return out

Expand Down Expand Up @@ -126,25 +123,25 @@ def idle_handler(self, widget):
if self.running:
return True

def key_press_event(self, widget, event) :
if event.string == "q" :
self.cellgrid.quit()
return True

if event.string == " " :
def key_press_event(self, widget, event):
if event.string == " ":
self.cellgrid.update(self.rule)
self.draw()
self.running = False
return True

if event.string == "c" :
elif event.string == "c":
Comment on lines -129 to +133
Copy link
Author

Choose a reason for hiding this comment

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

Function CAWindow.key_press_event refactored with the following changes:

  • Simplify conditional into switch-like form

if self.running:
return True
self.running = True
gobject.timeout_add(self.timeout, self.idle_handler,
self.drawing_area)
return True

elif event.string == "q":
self.cellgrid.quit()
return True

return False

def expose_handler(self, widget, event):
Expand Down
2 changes: 1 addition & 1 deletion cleanhtml.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def remove_empty_tags(soup):
innerhtml = t.text
# print "tag", t
# print "innerHTML", innerhtml
if not innerhtml or not innerhtml.strip():
if not (innerhtml and innerhtml.strip()):
Copy link
Author

Choose a reason for hiding this comment

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

Function remove_empty_tags refactored with the following changes:

  • Simplify logical expression

t.extract()

def prettyprint(soup):
Expand Down
68 changes: 31 additions & 37 deletions conjunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,7 @@

planets_by_name = ["Moon", "Mercury", "Venus", "Mars", "Jupiter", "Saturn"]

planets_up = {}
for planet in planets:
planets_up[planet.name] = None

planets_up = {planet.name: None for planet in planets}
Copy link
Author

Choose a reason for hiding this comment

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

Lines 59-62 refactored with the following changes:

  • Convert for loop into dictionary comprehension

saw_conjunction = False
visible_planets = []

Expand Down Expand Up @@ -223,11 +220,7 @@ def conjstr(b1, b2, sepdate, minsep):
if hour > sepdate_tuple[3]:
sepdate_tuple[2] -= 1
sepdate_tuple[3] = hour
if hour > 12:
hourstr = str(hour-12) + " pm"
else:
hourstr = str(hour) + " am"

hourstr = str(hour-12) + " pm" if hour > 12 else str(hour) + " am"
Comment on lines -226 to +223
Copy link
Author

Choose a reason for hiding this comment

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

Function Conjunction.closeout.conjstr refactored with the following changes:

  • Replace if statement with if expression

seps = "POSSIBLE OCCULTATION around " + hourstr
else:
seps = sepstr(minsep)
Expand Down Expand Up @@ -350,12 +343,8 @@ def finish_planet(p, d, observer, output_format):
observer.date = d
transit = observer.previous_transit(body) - ephem.hour * timezone
transit = list(ephem.Date(transit).tuple())
if transit[3] < 3 or transit[3] > 12:
when = "evening"
else:
when = "morning"

if p == "Venus" or p == "Mercury":
when = "evening" if transit[3] < 3 or transit[3] > 12 else "morning"
if p in ["Venus", "Mercury"]:
Comment on lines -353 to +347
Copy link
Author

Choose a reason for hiding this comment

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

Function finish_planet refactored with the following changes:

  • Replace if statement with if expression
  • Replace multiple comparisons of same variable with in operator
  • Simplify conditional into switch-like form
  • Split conditional into multiple branches
  • Merge duplicate blocks in conditional
  • Remove redundant conditional
  • Remove empty elif clause
  • Simplify logical expression

if when == "evening":
isvis = p + " is visible in the early evening sky."
else:
Expand Down Expand Up @@ -386,28 +375,33 @@ def finish_planet(p, d, observer, output_format):
isvis += '.'
crescents[p] = [ None, None ]

if output_format == "csv" or output_format == "sql":
if p != 'Moon':
if web_image[p]:
img = web_image[p][0]
cred = web_image[p][1]
w = web_image[p][2]
h = web_image[p][3]
else:
img = ""
cred = ""
w = ""
h = ""

if output_format == "csv":
print("%s,%s,%s,,%s,,%s,%s,%s,%s" % \
(p, datestr(planets_up[p]), datestr(d), isvis,
img, w, h, cred))
else:
print("('%s', 'astronomy', 'naked eye', '%s', '%s', '%s', '%s', %s, %s, '%s' )," % \
(p, datestr(planets_up[p]), datestr(d), isvis,
img, w, h, cred))
else:
if (
output_format == "csv"
and p != 'Moon'
or output_format != "csv"
and output_format == "sql"
and p != 'Moon'
):
if web_image[p]:
img = web_image[p][0]
cred = web_image[p][1]
w = web_image[p][2]
h = web_image[p][3]
else:
img = ""
cred = ""
w = ""
h = ""

if output_format == "csv":
print("%s,%s,%s,,%s,,%s,%s,%s,%s" % \
(p, datestr(planets_up[p]), datestr(d), isvis,
img, w, h, cred))
else:
print("('%s', 'astronomy', 'naked eye', '%s', '%s', '%s', '%s', %s, %s, '%s' )," % \
(p, datestr(planets_up[p]), datestr(d), isvis,
img, w, h, cred))
elif output_format not in ["csv", "sql"]:
print(datestr(planets_up[p]), "to", datestr(d), ":", isvis)

planets_up[p] = None
Expand Down
2 changes: 1 addition & 1 deletion countsyl
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def count_syllables(word):
if verbose: print("new syllable")
minsyl += 1
maxsyl += 1
elif on_vowel and not in_diphthong and c != lastchar:
elif not in_diphthong and c != lastchar:
Copy link
Author

Choose a reason for hiding this comment

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

Function count_syllables refactored with the following changes:

  • Remove redundant conditional

# We were already in a vowel.
# Don't increment anything except the max count,
# and only do that once per diphthong.
Expand Down
8 changes: 2 additions & 6 deletions decodemail.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,7 @@ def decode_piece(piece):
# anything about whether part[0] is str or bytes.
# So you have to check the type.
for part in decode_header(piece):
if type(part[0]) is bytes:
ret += part[0].decode(errors='replace')
else:
ret += part[0]

ret += part[0].decode(errors='replace') if type(part[0]) is bytes else part[0]
Copy link
Author

Choose a reason for hiding this comment

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

Function decode_piece refactored with the following changes:

  • Replace if statement with if expression

# Special case: the header itself comes out with charset None
# and decode doesn't add a space between it and the next part,
# even though there was a space in the original. So add one
Expand Down Expand Up @@ -159,7 +155,7 @@ def decode_file(filename, header_wanted, all=False, casematch=False):
all = False

if len(sys.argv) > 2:
if sys.argv[1] == '-h' or sys.argv[1] == '--help':
if sys.argv[1] in ['-h', '--help']:
Comment on lines -162 to +158
Copy link
Author

Choose a reason for hiding this comment

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

Lines 162-162 refactored with the following changes:

  • Replace multiple comparisons of same variable with in operator

print(Usage)
sys.exit(1)

Expand Down
Loading