def average(numbers, type='mean'):
import statistics
type = type.lower()
try:
statistics.mean(numbers)
except:
raise RuntimeError('An Error Has Occured: List Not Specified (0018)')
if type == 'mean':
return statistics.mean(numbers)
elif type == 'mode':
return statistics.mode(numbers)
elif type == 'median':
return statistics.median(numbers)
elif type == 'min':
return min(numbers)
elif type == 'max':
return max(numbers)
elif type == 'range':
return max(numbers) - min(numbers)
else:
raise RuntimeError('An Error Has Occured: You Entered An Invalid Operation (0003)')
# Throw A Runtime Error
python类Error()的实例源码
def dirtool(operation, directory):
operation = operation.lower()
import os
if operation == 'exists':
return bool(os.path.exists(directory))
elif operation == 'create':
if os.path.exists(directory):
raise RuntimeError('An Error Has Occured: Directory Already Exists (0007)')
else:
os.makedirs(directory)
elif operation == 'delete':
if os.path.exists(directory):
os.rmdir(directory)
else:
raise RuntimeError('An Error Has Occured: Directory Doesn\'t Exist (0009)')
else:
raise RuntimeError('An Error Has Occured: Invalid Operation Entered (0008)')
# Download A File
def convertsymbol(value, command):
command = command.lower()
if command == 'to':
try:
return chr(value)
except ValueError:
raise RuntimeError('Invalid Symbol Value (0014)')
elif command == 'from':
try:
return ord(value)
except ValueError:
raise RuntimeError('Invalid Symbol (0015)')
else:
raise RuntimeError('An Error Has Occured: Invalid Operation Entered (0008)')
# Get The Type Of A Value
def availchar(charactertype):
import string
if charactertype == 'letters':
return string.ascii_letters
elif charactertype == 'lowercase':
return string.ascii_lowercase
elif charactertype == 'uppercase':
return string.ascii_uppercase
elif charactertype == 'digits':
return string.digits
elif charactertype == 'hexdigits':
return string.hexdigits
elif charactertype == 'punctuation':
return string.punctuation
elif charactertype == 'printable':
return string.printable
elif charactertype == 'whitespace':
return string.whitespace
else:
raise RuntimeError('An Error Has Occured: Invalid Operation Entered (0008)')
# Get The Value Of A Word
def fetchStreamURL(video_id):
cdn_url = "http://getcdn.hotstar.com/AVS/besc?action=GetCDN&asJson=Y&channel=TABLET&id=" + video_id + "&type=VOD"
response = r.get(cdn_url)
if str(response) == '<Response [200]>':
json_response = json.loads(response.text.encode('utf-8'))
stream_url = json_response['resultObj']['src'].encode('utf-8')
else:
print('HTTP Error. Unable to connect to Hotstar. Exiting.\n')
sys.exit(0)
return stream_url
def submit(probID, path=None, language=None, website=None):
global websiteObject
# login(website)
result = websiteObject.submit(probID, path, language)
if result is None:
print("Error submitting")
return
table = prettytable.PrettyTable(result[0])
for row in result[1:]:
table.add_row(row)
print(str(table))
def open_question(probID, web=None):
global pref_manager
global websiteObject
login()
if webbrowser is None:
web = pref_manager.get("browser")
try:
browser = webbrowser.get(web)
except webbrowser.Error:
print("Invalid browser")
return
browser.open(websiteObject.get_question(probID))
def browser_available():
try:
webbrowser.get()
return True
except webbrowser.Error:
return False
def _prompt_user_for_token(url, token_type):
"""Get Token from user
:param url: url for user to go to
:type url: str
:param token_type: type of token to be received
:type token_type: str
:returns: token show to user by browser
:rtype: str
"""
msg = textwrap.dedent("""\
If your browser didn't open, please go to the following link:
{url}
Enter {token_type}: """)
msg = msg.lstrip().format(url=url, token_type=token_type)
try:
webbrowser.open_new_tab(url)
except webbrowser.Error as exc:
logger.warning(
'Exception occurred while calling webbrowser.open(%r): %s',
url, exc,
)
pass
sys.stderr.write(msg)
sys.stderr.flush()
token = sys.stdin.readline().strip()
return token
def download(self):
try:
webbrowser.open(self.source)
except webbrowser.Error:
pass
def list_files(self, *largs):
print('display thread')
self.ids.grid.clear_widgets()
# self.ids.spinner.active = True
url = 'http://ahmedpartey.com/sermons/'
try:
r = requests.get(url)
thread.start_new_thread(self.go, ('name',))
except requests.exceptions.ConnectionError:
# print('cant connect')
# self.ids.spinner.active = False
self.login_failure('Connection Error')
# Snackbar.make('Connection Error, Try Again')
else:
url = 'http://ahmedpartey.com/sermons/'
d = requests.get(url)
o = d.text
dom = Html().feed(o)
for ind in dom.find('a'):
if ind.text()[-4:] == '.mp3':
self.passed.append(str(ind.text()))
self.ids.spinner.active = False
# print(self.passed)
for track in self.passed:
src = 'http://ahmedpartey.com/sermons/{}'.format(track)
# print(src)
self.links.append(src)
self.album = AudioButton(text=str(track))
self.album.add_widget(Photo(source='./assets/tower.png'))
self.ids.grid.add_widget(self.album)
self.ids.spinner.active = False
# print(self.links)
def plot_map(df):
'''
This function creates a html file contain all in data in dataframe,
then it will open automatically in google chrome, and recommendated information will
be marked in google map.
Parameter:
df is the dataframe(sorted nearby locations) with lat & lng
Exception:
IOError
'''
path = os.path.abspath("Plot")
try:
fh = codecs.open(path + '/locations.js','w', "utf-8")
fh.write("locations = [\n")
count = 0
output= []
for i in range(df.shape[0]):
lat = df['Lat'].iloc[i]
lng = df['Lng'].iloc[i]
name = df['Name'].iloc[i]
address = df['Address'].iloc[i].strip()
output = "["+str(lat)+","+str(lng)+", \""+name+"\", "+ "\""+str(address)+"\"]"
fh.write(output)
if i < df.shape[0]-1:
fh.write(",\n")
else:
fh.write("\n];\n")
fh.close()
base = os.getcwd()
link = 'file://' + base + '/Plot/plot_map.html'
webbrowser.open_new_tab(link)
except IOError:
print("Error: can\'t find file or read data")
except webbrowser.Error:
print("Error: can't open web browser.")
def debugstate(state):
if state == 'Enable':
debugenabled = True
print('Debug Mode Has Been Enabled')
elif state == 'Disable':
debugenabled = False
print('Debug Mode Has Been Disabled')
else:
raise RuntimeError('An Error Has Occured: Invalid Debug State Entered (0005)')
# DEBUG: Make ROS Code Variables Global
def debug_varglobal():
if debugenabled == True:
global ros_output
global ros_stored
else:
raise RuntimeError('An Error Has Occured: Debug Mode Not Enabled (0006)')
# DEBUG: Supress All Warnings
def debug_supresswarnings():
if debugenabled == True:
import warnings
warnings.filterwarnings("ignore")
else:
raise RuntimeError('An Error Has Occured: Debug Mode Not Enabled (0006)')
# Check If A Number Is A Prime Number
def equation(operation, firstnum, secondnum):
if not isnumber(firstnum) and isnumber(secondnum):
raise RuntimeError('An Error Has Occured: One Of The Values Specified Is Not A Number (0002)')
if operation == 'plus':
return (firstnum + secondnum)
elif operation == 'minus':
return (firstnum - secondnum)
elif operation == 'multiply':
return (firstnum * secondnum)
elif operation == 'divide':
return (firstnum / secondnum)
else:
raise RuntimeError('An Error Has Occured: You Entered An Invalid Operation (0003)')
# Preform Scientific Operations
def length(value):
try:
return len(convertstring(value))
except OverflowError:
raise RuntimeError('An Error Has Occured: The Length Exceeds The Limit (', charlimit(), ') (0015)')
# Simulate A Cow Saying Text
def less_or_equal(number):
import math
try:
return math.floor(number)
except:
raise RuntimeError('An Error Has Occured: Number Not Provided (0016)')
# Join Two Strings
def filedownload(source, destination):
import urllib
if not isempty(source):
if not isempty(destination):
try:
urllib.request.urlretrieve(source, destination)
except:
raise RuntimeError('An Error Has Occured: File Download Error (0010)')
else:
raise RuntimeError('An Error Has Occured: Source Or Destination Invalid (0011)')
else:
raise RuntimeError('An Error Has Occured: Source Or Destination Invalid (0011)')
# Tools For Files (If Exists, Make And Delete)
def file(operation, path):
operation = operation.lower()
if operation == 'exists':
import os.path
return bool(os.path.isfile(path))
elif operation == 'read':
if file('exists', path):
F = open(path, "w")
return F
else:
raise RuntimeError('An Error Has Occured: File Not Found (0012)')
elif operation == 'delete':
import os
if file('exists', path):
os.remove(path)
else:
raise RuntimeError('An Error Has Occured: File Not Found (0012)')
elif operation == 'create':
if not file('exists', path):
f = open(path, "w+")
f.close()
else:
raise RuntimeError('An Error Has Occured: File Already Exists (0013)')
else:
raise RuntimeError('An Error Has Occured: Invalid Operation Entered (0008)')
# Tools For Text Files
def yearlimit(limittype):
import datetime
if limittype == 'min':
return datetime.MINYEAR
elif limittype == 'max':
return datetime.MAXYEAR
else:
raise RuntimeError('An Error Has Occured: Invalid Operation Entered (0008)')
# Get The Timezone Code
def openurl(url):
import webbrowser
try:
webbrowser.open(url)
except webbrowser.Error:
raise RuntimeError('An Error Has Occured: Unable To Open URL (0017)')
# Open A Link In A New Window Of A Webbrowser
def newwindow(url):
import webbrowser
try:
webbrowser.open_new(url)
except webbrowser.Error:
raise RuntimeError('An Error Has Occured: Unable To Open URL (0017)')
# Open A Link In A New Tab Of A Webbrowser
def randomstr(valuelist):
from random import choice
try:
return choice(valuelist)
except IndexError:
raise RuntimeError('An Error Has Occured: List Not Specified (0018)')
# Get The Time Since 00:00 On 1 January 1970
def openStream(stream_url):
global quality, stream_url_hls, streams
print(
'''
----------------- Menu -----------------
1. Open stream in default Browser
2. Open stream in default Media Player
3. Copy link to clipboard
4. Display link on console
5. Exit
''')
choice = raw_input('Enter choice : ')
try:
choice = int(choice)
except ValueError:
print('Please enter an integer. Exiting.\n')
sys.exit(0)
if choice == 1:
try:
browser = wb.get('safari')
except wb.Error:
try:
browser = wb.get('chrome')
except wb.Error:
try:
browser = wb.get('google-chrome')
except wb.Error:
browser = wb.get()
browser.open_new_tab(stream_url)
elif choice == 2:
os.system("livestreamer '" + stream_url_hls + "' '" + quality + "'")
#os.system("vlc " + stream_url)
elif choice == 3:
pyperclip.copy(stream_url)
print('Streaming link copied to clipboard.\n')
elif choice == 4:
print('Stream link : %s\n' % stream_url)
elif choice == 5:
print('Exiting.\n')
sys.exit(0)
else:
print('Incorrect choice. Exiting.\n')
sys.exit(0)
def start(browser=False, debug=False):
""" Start a bottle web server.
Derived from WSGIRefServer.run()
to have control over the main loop.
"""
global DEBUG
DEBUG = debug
class FixedHandler(wsgiref.simple_server.WSGIRequestHandler):
def address_string(self): # Prevent reverse DNS lookups please.
return self.client_address[0]
def log_request(*args, **kw):
if debug:
return wsgiref.simple_server.WSGIRequestHandler.log_request(*args, **kw)
S.server = wsgiref.simple_server.make_server(
conf['network_host'],
conf['network_port'],
bottle.default_app(),
wsgiref.simple_server.WSGIServer,
FixedHandler
)
S.server.timeout = 0.01
S.server.quiet = not debug
if debug:
bottle.debug(True)
print "Internal storage root is: " + conf['rootdir']
print "Persistent storage root is: " + conf['stordir']
print "-----------------------------------------------------------------------------"
print "Starting server at http://%s:%d/" % ('127.0.0.1', conf['network_port'])
print "-----------------------------------------------------------------------------"
driveboard.connect_withfind()
# open web-browser
if browser:
try:
webbrowser.open_new_tab('http://127.0.0.1:'+str(conf['network_port']))
except webbrowser.Error:
print "Cannot open Webbrowser, please do so manually."
sys.stdout.flush() # make sure everything gets flushed
# start server
print "INFO: Starting web server thread."
S.start()