[tor-commits] [stem/master] Run static checks on examples

atagar at torproject.org atagar at torproject.org
Fri Oct 2 23:16:05 UTC 2020


commit cef22e37c41de84b702e63b38ffaf3404069fefa
Author: Damian Johnson <atagar at torproject.org>
Date:   Fri Oct 2 15:08:41 2020 -0700

    Run static checks on examples
---
 .../example/benchmark_server_descriptor_stem.py    |  2 +
 docs/_static/example/benchmark_stem.py             |  6 ++-
 docs/_static/example/check_digests.py              | 10 ++---
 docs/_static/example/client_usage_using_pycurl.py  | 10 ++---
 .../_static/example/client_usage_using_socksipy.py |  6 +--
 docs/_static/example/create_descriptor.py          |  4 +-
 docs/_static/example/current_descriptors.py        |  4 +-
 docs/_static/example/custom_path_selection.py      |  3 +-
 docs/_static/example/descriptor_from_orport.py     |  4 +-
 .../example/descriptor_from_tor_control_socket.py  |  2 +-
 docs/_static/example/download_descriptor.py        |  1 +
 docs/_static/example/ephemeral_hidden_services.py  |  6 +--
 docs/_static/example/event_listening.py            |  6 +++
 docs/_static/example/exit_used.py                  | 15 +++----
 docs/_static/example/fibonacci_multiprocessing.py  |  5 ++-
 docs/_static/example/fibonacci_threaded.py         |  5 ++-
 docs/_static/example/hello_world.py                |  6 +--
 docs/_static/example/manual_config_options.py      |  5 +--
 docs/_static/example/outdated_relays.py            | 10 ++---
 .../persisting_a_consensus_with_parse_file.py      |  2 +-
 docs/_static/example/reading_twitter.py            | 49 +++++++++++++---------
 .../example/resuming_ephemeral_hidden_service.py   |  4 +-
 docs/_static/example/running_hidden_service.py     |  8 ++--
 docs/_static/example/tor_descriptors.py            |  7 +++-
 docs/_static/example/utilities.py                  |  8 ++--
 .../example/votes_by_bandwidth_authorities.py      |  2 +-
 test/task.py                                       |  1 +
 27 files changed, 112 insertions(+), 79 deletions(-)

diff --git a/docs/_static/example/benchmark_server_descriptor_stem.py b/docs/_static/example/benchmark_server_descriptor_stem.py
index c475652e..5154b6e7 100644
--- a/docs/_static/example/benchmark_server_descriptor_stem.py
+++ b/docs/_static/example/benchmark_server_descriptor_stem.py
@@ -1,6 +1,7 @@
 import time
 import stem.descriptor
 
+
 def measure_average_advertised_bandwidth(path):
   start_time = time.time()
   total_bw, count = 0, 0
@@ -17,5 +18,6 @@ def measure_average_advertised_bandwidth(path):
   print('  Time per server descriptor: %0.5f seconds' % (runtime / count))
   print('')
 
+
 if __name__ == '__main__':
   measure_average_advertised_bandwidth('server-descriptors-2015-11.tar')
diff --git a/docs/_static/example/benchmark_stem.py b/docs/_static/example/benchmark_stem.py
index 7094c3dd..ab94d960 100644
--- a/docs/_static/example/benchmark_stem.py
+++ b/docs/_static/example/benchmark_stem.py
@@ -1,6 +1,7 @@
 import time
 import stem.descriptor
 
+
 def measure_average_advertised_bandwidth(path):
   start_time = time.time()
   total_bw, count = 0, 0
@@ -17,6 +18,7 @@ def measure_average_advertised_bandwidth(path):
   print('  Time per server descriptor: %0.5f seconds' % (runtime / count))
   print('')
 
+
 def measure_countries_v3_requests(path):
   start_time = time.time()
   countries, count = set(), 0
@@ -35,6 +37,7 @@ def measure_countries_v3_requests(path):
   print('  Time per extrainfo descriptor: %0.5f seconds' % (runtime / count))
   print('')
 
+
 def measure_average_relays_exit(path):
   start_time = time.time()
   total_relays, exits, consensuses = 0, 0, 0
@@ -56,6 +59,7 @@ def measure_average_relays_exit(path):
   print('  Time per consensus: %0.5f seconds' % (runtime / consensuses))
   print('')
 
+
 def measure_fraction_relays_exit_80_microdescriptors(path):
   start_time = time.time()
   exits, count = 0, 0
@@ -74,9 +78,9 @@ def measure_fraction_relays_exit_80_microdescriptors(path):
   print('  Time per microdescriptor: %0.5f seconds' % (runtime / count))
   print('')
 
+
 if __name__ == '__main__':
   measure_average_advertised_bandwidth('/home/atagar/Desktop/server-descriptors-2015-11.tar')
   measure_countries_v3_requests('/home/atagar/Desktop/extra-infos-2015-11.tar')
   measure_average_relays_exit('/home/atagar/Desktop/consensuses-2015-11.tar')
   measure_fraction_relays_exit_80_microdescriptors('/home/atagar/Desktop/microdescs-2015-11.tar')
-
diff --git a/docs/_static/example/check_digests.py b/docs/_static/example/check_digests.py
index 93b037c0..2807c4d7 100644
--- a/docs/_static/example/check_digests.py
+++ b/docs/_static/example/check_digests.py
@@ -42,16 +42,16 @@ def validate_relay(fingerprint):
     sys.exit(1)
 
   if router_status_entry.digest == server_desc.digest():
-    print("Server descriptor digest is correct")
+    print('Server descriptor digest is correct')
   else:
-    print("Server descriptor digest invalid, expected %s but is %s" % (router_status_entry.digest, server_desc.digest()))
+    print('Server descriptor digest invalid, expected %s but is %s' % (router_status_entry.digest, server_desc.digest()))
 
   if server_desc.extra_info_digest == extrainfo_desc.digest():
-    print("Extrainfo descriptor digest is correct")
+    print('Extrainfo descriptor digest is correct')
   else:
-    print("Extrainfo descriptor digest invalid, expected %s but is %s" % (server_desc.extra_info_digest, extrainfo_desc.digest()))
+    print('Extrainfo descriptor digest invalid, expected %s but is %s' % (server_desc.extra_info_digest, extrainfo_desc.digest()))
 
 
 if __name__ == '__main__':
-  fingerprint = raw_input("What relay fingerprint would you like to validate?\n")
+  fingerprint = input('What relay fingerprint would you like to validate?\n')
   validate_relay(fingerprint)
diff --git a/docs/_static/example/client_usage_using_pycurl.py b/docs/_static/example/client_usage_using_pycurl.py
index 48ebdac0..5ef31f67 100644
--- a/docs/_static/example/client_usage_using_pycurl.py
+++ b/docs/_static/example/client_usage_using_pycurl.py
@@ -26,7 +26,7 @@ def query(url):
     query.perform()
     return output.getvalue()
   except pycurl.error as exc:
-    return "Unable to reach %s (%s)" % (url, exc)
+    return 'Unable to reach %s (%s)' % (url, exc)
 
 
 # Start an instance of Tor configured to only exit through Russia. This prints
@@ -34,11 +34,11 @@ def query(url):
 # work if you have another Tor instance running.
 
 def print_bootstrap_lines(line):
-  if "Bootstrapped " in line:
+  if 'Bootstrapped ' in line:
     print(term.format(line, term.Color.BLUE))
 
 
-print(term.format("Starting Tor:\n", term.Attr.BOLD))
+print(term.format('Starting Tor:\n', term.Attr.BOLD))
 
 tor_process = stem.process.launch_tor_with_config(
   config = {
@@ -48,7 +48,7 @@ tor_process = stem.process.launch_tor_with_config(
   init_msg_handler = print_bootstrap_lines,
 )
 
-print(term.format("\nChecking our endpoint:\n", term.Attr.BOLD))
-print(term.format(query("https://www.atagar.com/echo.php"), term.Color.BLUE))
+print(term.format('\nChecking our endpoint:\n', term.Attr.BOLD))
+print(term.format(query('https://www.atagar.com/echo.php'), term.Color.BLUE))
 
 tor_process.kill()  # stops tor
diff --git a/docs/_static/example/client_usage_using_socksipy.py b/docs/_static/example/client_usage_using_socksipy.py
index 6f532d51..b0a8e103 100644
--- a/docs/_static/example/client_usage_using_socksipy.py
+++ b/docs/_static/example/client_usage_using_socksipy.py
@@ -11,10 +11,8 @@ socket.socket = socks.socksocket
 
 # Perform DNS resolution through the socket
 
-def getaddrinfo(*args):
-  return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
+socket.getaddrinfo = lambda *args: [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
 
-socket.getaddrinfo = getaddrinfo
 
 def query(url):
   """
@@ -24,4 +22,4 @@ def query(url):
   try:
     return urllib.urlopen(url).read()
   except:
-    return "Unable to reach %s" % url
+    return 'Unable to reach %s' % url
diff --git a/docs/_static/example/create_descriptor.py b/docs/_static/example/create_descriptor.py
index 29c5654f..c7e33ced 100644
--- a/docs/_static/example/create_descriptor.py
+++ b/docs/_static/example/create_descriptor.py
@@ -2,8 +2,8 @@ from stem.descriptor.server_descriptor import RelayDescriptor
 
 # prints 'caerSidi (71.35.133.197:9001)'
 desc = RelayDescriptor.create()
-print("%s (%s:%s)" % (desc.nickname, desc.address, desc.or_port))
+print('%s (%s:%s)' % (desc.nickname, desc.address, desc.or_port))
 
 # prints 'demo (127.0.0.1:80)'
 desc = RelayDescriptor.create({'router': 'demo 127.0.0.1 80 0 0'})
-print("%s (%s:%s)" % (desc.nickname, desc.address, desc.or_port))
+print('%s (%s:%s)' % (desc.nickname, desc.address, desc.or_port))
diff --git a/docs/_static/example/current_descriptors.py b/docs/_static/example/current_descriptors.py
index 7d44c664..87c343ef 100644
--- a/docs/_static/example/current_descriptors.py
+++ b/docs/_static/example/current_descriptors.py
@@ -2,6 +2,6 @@ import stem.descriptor.remote
 
 try:
   for desc in stem.descriptor.remote.get_consensus():
-    print("found relay %s (%s)" % (desc.nickname, desc.fingerprint))
+    print('found relay %s (%s)' % (desc.nickname, desc.fingerprint))
 except Exception as exc:
-  print("Unable to retrieve the consensus: %s" % exc)
+  print('Unable to retrieve the consensus: %s' % exc)
diff --git a/docs/_static/example/custom_path_selection.py b/docs/_static/example/custom_path_selection.py
index 551f7b2f..4851dc3b 100644
--- a/docs/_static/example/custom_path_selection.py
+++ b/docs/_static/example/custom_path_selection.py
@@ -15,6 +15,7 @@ EXIT_FINGERPRINT = '379FB450010D17078B3766C2273303C358C3A442'
 SOCKS_PORT = 9050
 CONNECTION_TIMEOUT = 30  # timeout before we give up on a circuit
 
+
 def query(url):
   """
   Uses pycurl to fetch a site using the proxy on the SOCKS_PORT.
@@ -34,7 +35,7 @@ def query(url):
     query.perform()
     return output.getvalue()
   except pycurl.error as exc:
-    raise ValueError("Unable to reach %s (%s)" % (url, exc))
+    raise ValueError('Unable to reach %s (%s)' % (url, exc))
 
 
 def scan(controller, path):
diff --git a/docs/_static/example/descriptor_from_orport.py b/docs/_static/example/descriptor_from_orport.py
index 48b0673b..32401d1b 100644
--- a/docs/_static/example/descriptor_from_orport.py
+++ b/docs/_static/example/descriptor_from_orport.py
@@ -9,6 +9,6 @@ try:
   )
 
   for desc in consensus:
-    print("found relay %s (%s)" % (desc.nickname, desc.fingerprint))
+    print('found relay %s (%s)' % (desc.nickname, desc.fingerprint))
 except Exception as exc:
-  print("Unable to retrieve the consensus: %s" % exc)
+  print('Unable to retrieve the consensus: %s' % exc)
diff --git a/docs/_static/example/descriptor_from_tor_control_socket.py b/docs/_static/example/descriptor_from_tor_control_socket.py
index 349f6f65..9a77ac33 100644
--- a/docs/_static/example/descriptor_from_tor_control_socket.py
+++ b/docs/_static/example/descriptor_from_tor_control_socket.py
@@ -4,4 +4,4 @@ with Controller.from_port(port = 9051) as controller:
   controller.authenticate()
 
   for desc in controller.get_network_statuses():
-    print("found relay %s (%s)" % (desc.nickname, desc.fingerprint))
+    print('found relay %s (%s)' % (desc.nickname, desc.fingerprint))
diff --git a/docs/_static/example/download_descriptor.py b/docs/_static/example/download_descriptor.py
index 89ea4a6c..8c8de3aa 100644
--- a/docs/_static/example/download_descriptor.py
+++ b/docs/_static/example/download_descriptor.py
@@ -125,5 +125,6 @@ def main(argv):
   if desc:
     print(desc)
 
+
 if __name__ == '__main__':
   main(sys.argv[1:])
diff --git a/docs/_static/example/ephemeral_hidden_services.py b/docs/_static/example/ephemeral_hidden_services.py
index 8ca3ab68..cebbd9e2 100644
--- a/docs/_static/example/ephemeral_hidden_services.py
+++ b/docs/_static/example/ephemeral_hidden_services.py
@@ -6,7 +6,7 @@ app = Flask(__name__)
 
 @app.route('/')
 def index():
-  return "<h1>Hi Grandma!</h1>"
+  return '<h1>Hi Grandma!</h1>'
 
 
 print(' * Connecting to tor')
@@ -18,9 +18,9 @@ with Controller.from_port() as controller:
   # port 5000 (this is where Flask runs by default).
 
   response = controller.create_ephemeral_hidden_service({80: 5000}, await_publication = True)
-  print(" * Our service is available at %s.onion, press ctrl+c to quit" % response.service_id)
+  print(' * Our service is available at %s.onion, press ctrl+c to quit' % response.service_id)
 
   try:
     app.run()
   finally:
-    print(" * Shutting down our hidden service")
+    print(' * Shutting down our hidden service')
diff --git a/docs/_static/example/event_listening.py b/docs/_static/example/event_listening.py
index b808a977..6790cf0b 100644
--- a/docs/_static/example/event_listening.py
+++ b/docs/_static/example/event_listening.py
@@ -23,6 +23,7 @@ GRAPH_HEIGHT = 8
 DOWNLOAD_COLOR = 'green'
 UPLOAD_COLOR = 'blue'
 
+
 def main():
   with Controller.from_port(port = 9051) as controller:
     controller.authenticate()
@@ -36,6 +37,7 @@ def main():
     except KeyboardInterrupt:
       pass  # the user hit ctrl+c
 
+
 def draw_bandwidth_graph(stdscr, controller):
   window = Window(stdscr)
 
@@ -59,6 +61,7 @@ def draw_bandwidth_graph(stdscr, controller):
 
   stdscr.getch()
 
+
 def _handle_bandwidth_event(window, bandwidth_rates, event):
   # callback for when tor provides us with a BW event
 
@@ -66,6 +69,7 @@ def _handle_bandwidth_event(window, bandwidth_rates, event):
   bandwidth_rates = bandwidth_rates[:GRAPH_WIDTH]  # truncate old values
   _render_graph(window, bandwidth_rates)
 
+
 def _render_graph(window, bandwidth_rates):
   window.erase()
 
@@ -106,6 +110,7 @@ def _render_graph(window, bandwidth_rates):
 
   window.refresh()
 
+
 class Window(object):
   """
   Simple wrapper for the curses standard screen object.
@@ -173,5 +178,6 @@ class Window(object):
   def refresh(self):
     self._stdscr.refresh()
 
+
 if __name__ == '__main__':
   main()
diff --git a/docs/_static/example/exit_used.py b/docs/_static/example/exit_used.py
index fde2db84..296b0864 100644
--- a/docs/_static/example/exit_used.py
+++ b/docs/_static/example/exit_used.py
@@ -3,9 +3,10 @@ import functools
 from stem import StreamStatus
 from stem.control import EventType, Controller
 
+
 def main():
   print("Tracking requests for tor exits. Press 'enter' to end.")
-  print("")
+  print('')
 
   with Controller.from_port() as controller:
     controller.authenticate()
@@ -23,12 +24,12 @@ def stream_event(controller, event):
     exit_fingerprint = circ.path[-1][0]
     exit_relay = controller.get_network_status(exit_fingerprint)
 
-    print("Exit relay for our connection to %s" % (event.target))
-    print("  address: %s:%i" % (exit_relay.address, exit_relay.or_port))
-    print("  fingerprint: %s" % exit_relay.fingerprint)
-    print("  nickname: %s" % exit_relay.nickname)
-    print("  locale: %s" % controller.get_info("ip-to-country/%s" % exit_relay.address, 'unknown'))
-    print("")
+    print('Exit relay for our connection to %s' % (event.target))
+    print('  address: %s:%i' % (exit_relay.address, exit_relay.or_port))
+    print('  fingerprint: %s' % exit_relay.fingerprint)
+    print('  nickname: %s' % exit_relay.nickname)
+    print('  locale: %s' % controller.get_info('ip-to-country/%s' % exit_relay.address, 'unknown'))
+    print('')
 
 
 if __name__ == '__main__':
diff --git a/docs/_static/example/fibonacci_multiprocessing.py b/docs/_static/example/fibonacci_multiprocessing.py
index 4ad3fe48..dc6ed125 100644
--- a/docs/_static/example/fibonacci_multiprocessing.py
+++ b/docs/_static/example/fibonacci_multiprocessing.py
@@ -1,11 +1,13 @@
 import stem.util.system
 import time
 
+
 def fibonacci(n):
   if n < 2:
     return n
   else:
-    return fibonacci(n-2) + fibonacci(n-1)
+    return fibonacci(n - 2) + fibonacci(n - 1)
+
 
 def main():
   # calculate fibonacci sequences four times in parallel
@@ -20,5 +22,6 @@ def main():
 
   print('took %0.1f seconds' % (time.time() - start_time))
 
+
 if __name__ == '__main__':
   main()
diff --git a/docs/_static/example/fibonacci_threaded.py b/docs/_static/example/fibonacci_threaded.py
index 0e449122..9570f855 100644
--- a/docs/_static/example/fibonacci_threaded.py
+++ b/docs/_static/example/fibonacci_threaded.py
@@ -1,11 +1,13 @@
 import threading
 import time
 
+
 def fibonacci(n):
   if n < 2:
     return n
   else:
-    return fibonacci(n-2) + fibonacci(n-1)
+    return fibonacci(n - 2) + fibonacci(n - 1)
+
 
 def main():
   # calculate fibonacci sequences four times in parallel
@@ -24,5 +26,6 @@ def main():
 
   print('took %0.1f seconds' % (time.time() - start_time))
 
+
 if __name__ == '__main__':
   main()
diff --git a/docs/_static/example/hello_world.py b/docs/_static/example/hello_world.py
index 4e5df98e..cdf23f74 100644
--- a/docs/_static/example/hello_world.py
+++ b/docs/_static/example/hello_world.py
@@ -3,7 +3,7 @@ from stem.control import Controller
 with Controller.from_port(port = 9051) as controller:
   controller.authenticate()  # provide the password here if you set one
 
-  bytes_read = controller.get_info("traffic/read")
-  bytes_written = controller.get_info("traffic/written")
+  bytes_read = controller.get_info('traffic/read')
+  bytes_written = controller.get_info('traffic/written')
 
-  print("My Tor relay has read %s bytes and written %s." % (bytes_read, bytes_written))
+  print('My Tor relay has read %s bytes and written %s.' % (bytes_read, bytes_written))
diff --git a/docs/_static/example/manual_config_options.py b/docs/_static/example/manual_config_options.py
index 336634a3..d3f02c4a 100644
--- a/docs/_static/example/manual_config_options.py
+++ b/docs/_static/example/manual_config_options.py
@@ -4,9 +4,9 @@ from stem.util import term
 try:
   print("Downloading tor's manual information, please wait...")
   manual = Manual.from_remote()
-  print("  done\n")
+  print('  done\n')
 except OSError as exc:
-  print("  unsuccessful (%s), using information provided with stem\n" % exc)
+  print('  unsuccessful (%s), using information provided with stem\n' % exc)
   manual = Manual.from_cache()  # fall back to our bundled manual information
 
 print('Which tor configuration would you like to learn about?  (press ctrl+c to quit)\n')
@@ -27,4 +27,3 @@ try:
         print(term.format("Sorry, we don't have any information about %s. Are you sure it's an option?" % requested_option, term.Color.RED))
 except KeyboardInterrupt:
   pass  # user pressed ctrl+c
-
diff --git a/docs/_static/example/outdated_relays.py b/docs/_static/example/outdated_relays.py
index 67d0ea9a..6c21ef51 100644
--- a/docs/_static/example/outdated_relays.py
+++ b/docs/_static/example/outdated_relays.py
@@ -4,16 +4,16 @@ from stem.version import Version
 downloader = DescriptorDownloader()
 count, with_contact = 0, 0
 
-print("Checking for outdated relays...")
-print("")
+print('Checking for outdated relays...')
+print('')
 
 for desc in downloader.get_server_descriptors():
   if desc.tor_version < Version('0.2.3.0'):
     count += 1
 
     if desc.contact:
-      print('  %-15s %s' % (desc.tor_version, desc.contact.decode("utf-8", "replace")))
+      print('  %-15s %s' % (desc.tor_version, desc.contact.decode('utf-8', 'replace')))
       with_contact += 1
 
-print("")
-print("%i outdated relays found, %i had contact information" % (count, with_contact))
+print('')
+print('%i outdated relays found, %i had contact information' % (count, with_contact))
diff --git a/docs/_static/example/persisting_a_consensus_with_parse_file.py b/docs/_static/example/persisting_a_consensus_with_parse_file.py
index 4a78c468..160b3d4e 100644
--- a/docs/_static/example/persisting_a_consensus_with_parse_file.py
+++ b/docs/_static/example/persisting_a_consensus_with_parse_file.py
@@ -7,4 +7,4 @@ consensus = next(parse_file(
 ))
 
 for fingerprint, relay in consensus.routers.items():
-  print("%s: %s" % (fingerprint, relay.nickname))
+  print('%s: %s' % (fingerprint, relay.nickname))
diff --git a/docs/_static/example/reading_twitter.py b/docs/_static/example/reading_twitter.py
index 5709e1f4..48cf4b48 100644
--- a/docs/_static/example/reading_twitter.py
+++ b/docs/_static/example/reading_twitter.py
@@ -11,31 +11,41 @@ import socks  # SockiPy module
 import stem.process
 
 SOCKS_PORT = 7000
-TWITTER_API_URL = "https://api.twitter.com/1.1/statuses/user_timeline.json"
-CONSUMER_KEY = ""
-CONSUMER_SECRET = ""
-ACCESS_TOKEN = ""
-ACCESS_TOKEN_SECRET = ""
-
-HEADER_AUTH_KEYS = ['oauth_consumer_key', 'oauth_nonce', 'oauth_signature',
-  'oauth_signature_method', 'oauth_timestamp', 'oauth_token', 'oauth_version']
+TWITTER_API_URL = 'https://api.twitter.com/1.1/statuses/user_timeline.json'
+CONSUMER_KEY = ''
+CONSUMER_SECRET = ''
+ACCESS_TOKEN = ''
+ACCESS_TOKEN_SECRET = ''
+
+HEADER_AUTH_KEYS = [
+  'oauth_consumer_key',
+  'oauth_nonce',
+  'oauth_signature',
+  'oauth_signature_method',
+  'oauth_timestamp',
+  'oauth_token',
+  'oauth_version',
+]
 
 socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', SOCKS_PORT)
 socket.socket = socks.socksocket
 
+
 def oauth_signature(key_dict):
-  fin_key = ""
+  fin_key = ''
 
   for key in sorted(key_dict.keys()):
-    fin_key += key + "=" + key_dict[key] + "&"
+    fin_key += key + '=' + key_dict[key] + '&'
 
-  fin_key =  fin_key[:-1]
-  fin_key = 'GET' + "&" + urllib.quote(TWITTER_API_URL, '') + "&" + urllib.quote(fin_key, '')
-  key = urllib.quote(CONSUMER_SECRET, '') + "&" + urllib.quote(ACCESS_TOKEN_SECRET, '')
+  fin_key = fin_key[:-1]
+  fin_key = 'GET' + '&' + urllib.quote(TWITTER_API_URL, '') + '&' + urllib.quote(fin_key, '')
+  key = urllib.quote(CONSUMER_SECRET, '') + '&' + urllib.quote(ACCESS_TOKEN_SECRET, '')
   hashed = hmac.new(key, fin_key, hashlib.sha1)
   fin_key = binascii.b2a_base64(hashed.digest())[:-1]
+
   return urllib.quote(fin_key, '')
 
+
 def poll_twitter_feed(user_id, tweet_count):
   """
   Polls Twitter for the tweets from a given user.
@@ -44,7 +54,7 @@ def poll_twitter_feed(user_id, tweet_count):
   key_dict = {
     'oauth_consumer_key': urllib.quote(CONSUMER_KEY, ''),
     'oauth_nonce': urllib.quote(hashlib.md5(str(time.time())).hexdigest(), ''),
-    'oauth_signature_method': urllib.quote("HMAC-SHA1", ''),
+    'oauth_signature_method': urllib.quote('HMAC-SHA1', ''),
     'oauth_timestamp': urllib.quote(str(int(time.time())), ''),
     'oauth_token': urllib.quote(ACCESS_TOKEN, ''),
     'oauth_version': urllib.quote('1.0', ''),
@@ -60,15 +70,16 @@ def poll_twitter_feed(user_id, tweet_count):
   header_auth = 'OAuth ' + ', '.join(['%s="%s"' % (key, key_dict[key]) for key in HEADER_AUTH_KEYS])
 
   data = urllib.urlencode(url_values)
-  api_request = urllib2.Request(TWITTER_API_URL + "?" + data, headers = {'Authorization': header_auth})
+  api_request = urllib2.Request(TWITTER_API_URL + '?' + data, headers = {'Authorization': header_auth})
 
   try:
     api_response = urllib2.urlopen(api_request).read()
   except:
-    raise OSError("Unable to reach %s" % TWITTER_API_URL)
+    raise OSError('Unable to reach %s' % TWITTER_API_URL)
 
   return json.loads(api_response)
 
+
 tor_process = stem.process.launch_tor_with_config(
   config = {
     'SocksPort': str(SOCKS_PORT),
@@ -78,9 +89,9 @@ tor_process = stem.process.launch_tor_with_config(
 
 try:
   for index, tweet in enumerate(poll_twitter_feed('ioerror', 3)):
-    print("%i. %s" % (index + 1, tweet["created_at"]))
-    print(tweet["text"])
-    print("")
+    print('%i. %s' % (index + 1, tweet['created_at']))
+    print(tweet['text'])
+    print('')
 except OSError as exc:
   print(exc)
 finally:
diff --git a/docs/_static/example/resuming_ephemeral_hidden_service.py b/docs/_static/example/resuming_ephemeral_hidden_service.py
index 3277bce2..c03fe607 100644
--- a/docs/_static/example/resuming_ephemeral_hidden_service.py
+++ b/docs/_static/example/resuming_ephemeral_hidden_service.py
@@ -8,7 +8,7 @@ with Controller.from_port() as controller:
 
   if not os.path.exists(key_path):
     service = controller.create_ephemeral_hidden_service({80: 5000}, await_publication = True)
-    print("Started a new hidden service with the address of %s.onion" % service.service_id)
+    print('Started a new hidden service with the address of %s.onion' % service.service_id)
 
     with open(key_path, 'w') as key_file:
       key_file.write('%s:%s' % (service.private_key_type, service.private_key))
@@ -17,7 +17,7 @@ with Controller.from_port() as controller:
       key_type, key_content = key_file.read().split(':', 1)
 
     service = controller.create_ephemeral_hidden_service({80: 5000}, key_type = key_type, key_content = key_content, await_publication = True)
-    print("Resumed %s.onion" % service.service_id)
+    print('Resumed %s.onion' % service.service_id)
 
   input('press any key to shut the service down...')
   controller.remove_ephemeral_hidden_service(service.service_id)
diff --git a/docs/_static/example/running_hidden_service.py b/docs/_static/example/running_hidden_service.py
index 5392ef44..6e5fb03b 100644
--- a/docs/_static/example/running_hidden_service.py
+++ b/docs/_static/example/running_hidden_service.py
@@ -9,7 +9,7 @@ app = Flask(__name__)
 
 @app.route('/')
 def index():
-  return "<h1>Hi Grandma!</h1>"
+  return '<h1>Hi Grandma!</h1>'
 
 
 print(' * Connecting to tor')
@@ -25,14 +25,14 @@ with Controller.from_port() as controller:
   # Create a hidden service where visitors of port 80 get redirected to local
   # port 5000 (this is where Flask runs by default).
 
-  print(" * Creating our hidden service in %s" % hidden_service_dir)
+  print(' * Creating our hidden service in %s' % hidden_service_dir)
   result = controller.create_hidden_service(hidden_service_dir, 80, target_port = 5000)
 
   # The hostname is only available when we can read the hidden service
   # directory. This requires us to be running with the same user as tor.
 
   if result.hostname:
-    print(" * Our service is available at %s, press ctrl+c to quit" % result.hostname)
+    print(' * Our service is available at %s, press ctrl+c to quit' % result.hostname)
   else:
     print(" * Unable to determine our service's hostname, probably due to being unable to read the hidden service directory")
 
@@ -43,6 +43,6 @@ with Controller.from_port() as controller:
     # want to delete the hidden service directory if you'd like to have this
     # same *.onion address in the future.
 
-    print(" * Shutting down our hidden service")
+    print(' * Shutting down our hidden service')
     controller.remove_hidden_service(hidden_service_dir)
     shutil.rmtree(hidden_service_dir)
diff --git a/docs/_static/example/tor_descriptors.py b/docs/_static/example/tor_descriptors.py
index 708e5fcc..cfc86276 100644
--- a/docs/_static/example/tor_descriptors.py
+++ b/docs/_static/example/tor_descriptors.py
@@ -4,7 +4,9 @@ import stem.descriptor.remote
 
 from stem.util import str_tools
 
+
 # provides a mapping of observed bandwidth to the relay nicknames
+
 def get_bw_to_relay():
   bw_to_relay = {}
 
@@ -13,10 +15,11 @@ def get_bw_to_relay():
       if desc.exit_policy.is_exiting_allowed():
         bw_to_relay.setdefault(desc.observed_bandwidth, []).append(desc.nickname)
   except Exception as exc:
-    print("Unable to retrieve the server descriptors: %s" % exc)
+    print('Unable to retrieve the server descriptors: %s' % exc)
 
   return bw_to_relay
 
+
 # prints the top fifteen relays
 
 bw_to_relay = get_bw_to_relay()
@@ -24,7 +27,7 @@ count = 1
 
 for bw_value in sorted(bw_to_relay.keys(), reverse = True):
   for nickname in bw_to_relay[bw_value]:
-    print("%i. %s (%s/s)" % (count, nickname, str_tools.size_label(bw_value, 2)))
+    print('%i. %s (%s/s)' % (count, nickname, str_tools.size_label(bw_value, 2)))
     count += 1
 
     if count > 15:
diff --git a/docs/_static/example/utilities.py b/docs/_static/example/utilities.py
index 0e8f01fd..e7d7f7ea 100644
--- a/docs/_static/example/utilities.py
+++ b/docs/_static/example/utilities.py
@@ -10,7 +10,7 @@ if not resolvers:
   sys.exit(1)
 
 picked_resolver = resolvers[0]  # lets just opt for the first
-print("Our platform supports connection resolution via: %s (picked %s)" % (', '.join(resolvers), picked_resolver))
+print('Our platform supports connection resolution via: %s (picked %s)' % (', '.join(resolvers), picked_resolver))
 
 tor_pids = pid_by_name('tor', multiple = True)
 
@@ -20,9 +20,9 @@ if not tor_pids:
 elif len(tor_pids) > 1:
   print("You're running %i instances of tor, picking the one with pid %i" % (len(tor_pids), tor_pids[0]))
 else:
-  print("Tor is running with pid %i" % tor_pids[0])
+  print('Tor is running with pid %i' % tor_pids[0])
 
-print("\nConnections:\n")
+print('\nConnections:\n')
 
 for conn in get_connections(picked_resolver, process_pid = tor_pids[0], process_name = 'tor'):
-  print("  %s:%s => %s:%s" % (conn.local_address, conn.local_port, conn.remote_address, conn.remote_port))
+  print('  %s:%s => %s:%s' % (conn.local_address, conn.local_port, conn.remote_address, conn.remote_port))
diff --git a/docs/_static/example/votes_by_bandwidth_authorities.py b/docs/_static/example/votes_by_bandwidth_authorities.py
index 840d50d8..0cc737a1 100644
--- a/docs/_static/example/votes_by_bandwidth_authorities.py
+++ b/docs/_static/example/votes_by_bandwidth_authorities.py
@@ -29,4 +29,4 @@ for authority_name, query in queries.items():
     else:
       print('  %i measured entries and %i unmeasured' % (measured, unmeasured))
   except Exception as exc:
-    print("  failed to get the vote (%s)" % exc)
+    print('  failed to get the vote (%s)' % exc)
diff --git a/test/task.py b/test/task.py
index b21141c7..492ebe5d 100644
--- a/test/task.py
+++ b/test/task.py
@@ -62,6 +62,7 @@ SRC_PATHS = [os.path.join(test.STEM_BASE, path) for path in (
   'cache_fallback_directories.py',
   'setup.py',
   'tor-prompt',
+  os.path.join('docs', '_static', 'example'),
   os.path.join('docs', 'roles.py'),
 )]
 





More information about the tor-commits mailing list