def do_how_are_you(self, s):
"""Jarvis will inform you about his status."""
print_say("I am fine, How about you?", self, Fore.BLUE)
python类BLUE的实例源码
def do_os(self, s):
"""Displays information about your operating system."""
print_say('[!] Operating System Information', self, Fore.BLUE)
print_say('[*] ' + sys(), self, Fore.GREEN)
print_say('[*] ' + release(), self, Fore.GREEN)
print_say('[*] ' + dist()[0], self, Fore.GREEN)
for _ in architecture():
print_say('[*] ' + _, self, Fore.GREEN)
def help_umbrella(self):
"""Print info about umbrella command."""
print_say(
"If you're leaving your place, Jarvis will inform you if you might need an umbrella or not.", self,
Fore.BLUE)
def calc(s, self):
s = str.lower(s)
s = s.replace("power", "**")
s = s.replace("plus", "+")
s = s.replace("minus", "-")
s = s.replace("divided by", "/")
s = s.replace("by", "/")
s = s.replace("^", "**")
try:
x = eval(s)
print_say(str(x), self, Fore.BLUE)
except Exception:
print_say("Error : Not in correct format", self)
def scorecard(desc):
mid = match_id(desc)
data = c.scorecard(mid)
card = {}
card['matchinfo'] = "{}, {}".format(data['matchinfo']['mnum'], data['matchinfo']['mchdesc'])
card['status'] = "{}, {}".format(data['matchinfo']['mchstate'].title(), data['matchinfo']['status'])
card['scorecard'] = data['scorecard']
text = ''
text += Fore.LIGHTYELLOW_EX + card['matchinfo'] + '\n' + card['status'] + '\n\n'
text += Fore.BLACK + '*' * 35 + '\n\n'
for scr in reversed(card['scorecard']):
text += Fore.LIGHTYELLOW_EX + "{} {}\n{}/{} in {} overs\n\n".format(scr['batteam'], scr['inngdesc'], scr['runs'], scr['wickets'],
scr['overs'])
text += Fore.BLUE + "Batting\n"
text += Fore.RED + "{:<17} {:<3} {:<3} {:<3} {}\n\n".format('Name', 'R', 'B', '4', '6')
for b in scr['batcard']:
text += Fore.BLACK + "{:<17} {:<3} {:<3} {:<3} {}\n{}\n\n".format(b['name'], b['runs'], b['balls'], b['fours'], b['six'],
b['dismissal'])
text += Fore.LIGHTYELLOW_EX + "-" * 35 + "\n\n"
text += Fore.BLUE + "Bowling\n"
text += Fore.RED + "{:<17} {:<5} {:<3} {:<3} {}\n\n".format('Name', 'O', 'M', 'R', 'W')
for b in scr['bowlcard']:
text += Fore.BLACK + "{:<17} {:<5} {:<3} {:<3} {}\n\n".format(b['name'], b['overs'], b['maidens'], b['runs'],
b['wickets'])
text += Fore.BLUE + '*' * 35 + '\n\n'
return text
def main(self):
brain = Brain()
print_say("Ask me anything\n type 'leave' to stop", self, Fore.BLUE)
stay = True
while stay:
if six.PY2:
text = str.upper(raw_input(Fore.RED + ">> " + Fore.RESET))
else:
text = str.upper(input(Fore.RED + ">> " + Fore.RESET))
if text == "LEAVE":
print_say("thanks for talking to me", self)
stay = False
else:
print_say(brain.respond(text), self)
def weather(city=None):
if not city:
city = get_location()['city']
# Checks country
country = get_location()['country_name']
# If country is US, shows weather in Fahrenheit
if country == 'United States':
send_url = (
"http://api.openweathermap.org/data/2.5/weather?q={0}"
"&APPID=ab6ec687d641ced80cc0c935f9dd8ac9&units=imperial".format(
city)
)
unit = ' ºF in '
# If country is not US, shows weather in Celsius
else:
send_url = (
"http://api.openweathermap.org/data/2.5/weather?q={0}"
"&APPID=ab6ec687d641ced80cc0c935f9dd8ac9&units=metric".format(
city)
)
unit = ' ºC in '
r = requests.get(send_url)
j = json.loads(r.text)
# check if the city entered is not found
if 'message' in j and j['message'] == 'city not found':
print(Fore.BLUE + "City Not Found" + Fore.RESET)
return False
else:
temperature = j['main']['temp']
description = j['weather'][0]['main']
print(Fore.BLUE + "It's " + str(temperature) + unit +
str(city) + " (" + str(description) + ")" + Fore.RESET)
return True
def main(self, s):
# Trim input command to get only the location
loc = s.replace('weather', '').replace('in ', '').strip()
# Checks country
country = mapps.get_location()['country_name']
# If country is US, shows weather in Fahrenheit
if country == 'United States':
send_url = (
"http://api.openweathermap.org/data/2.5/weather?q={0}"
"&APPID=ab6ec687d641ced80cc0c935f9dd8ac9&units=imperial".format(
loc)
)
unit = ' ºF in '
# If country is not US, shows weather in Celsius
else:
send_url = (
"http://api.openweathermap.org/data/2.5/weather?q={0}"
"&APPID=ab6ec687d641ced80cc0c935f9dd8ac9&units=metric".format(loc)
)
unit = ' ºC in '
r = requests.get(send_url)
j = json.loads(r.text)
if 'message' in list(j.keys()) and ('city not found' in j['message'] or 'Nothing to geocode' in j['message']):
return pinpoint.main(Memory(), self, s)
temperature = j['main']['temp']
description = j['weather'][0]['main']
location = j['name']
print(Fore.BLUE + "It's " + str(temperature) + unit +
str(location.title()) + " (" + str(description) + ")" + Fore.RESET)
def print_say(text, self, color=""):
"""
This method give the jarvis the ability to print a text
and talk when sound is enable.
:param text: the text to print (or talk)
color: Fore.COLOR (ex Fore.BLUE), color for text
:return: Nothing to return.
"""
if self.enable_voice:
self.speech.text_to_speech(text)
print(color + text + Fore.RESET)
# Functions for printing user output
# TODO decide which ones use print_say instead of print
def info(string):
print(Fore.BLUE + string + Fore.RESET)
def load_ethers(self, path):
EthersManager.assert_readable(path)
lines = open(path, 'r').readlines()
print(Fore.BLUE + "The ethers file is")
print(''.join(lines))
for line in lines:
pieces = line.strip().split(' ')
if len(pieces) != 2: continue
mac, ip = pieces
self.ethers[mac] = ip
def _proceed_exec_result(out, err, ret_code, check_retcode):
err, out = force_unicode(err), force_unicode(out)
msg_parts = [
(Fore.RED if ret_code else Fore.GREEN, 'RetCode: ', str(ret_code)),
(Fore.BLUE, '=== StdOut ===\n', out),
(Fore.RED if err else Fore.GREEN, '=== StdErr ===\n', err)]
msg = '\n'.join(u'{}{}{}'.format(c, n, v) for c, n, v in msg_parts if v)
LOG.debug(msg + Style.RESET_ALL)
if check_retcode and ret_code != 0:
raise NonZeroRetCodeException(
stdout=out, stderr=err, ret_code=ret_code)
def query(sea):
url = "https://newsapi.org/v2/top-headlines?q=" + sea + "&apiKey="+ api_key
try:
with urlopen(url) as httpob:
decob = httpob.read().decode("utf-8")
jsonob = json.loads(decob)
news = jsonob["articles"]
# if api key is Invalid an HTTPError will be thrown.
except HTTPError as e:
print("Invalid API")
create_api_file(file_name)
return console()
# draws a border to seperate posts.
draw_border()
for n in news:
print(Fore.RESET)
temp = n["source"]
print(Back.YELLOW + src2(temp["name"]) + Back.RESET)
try:
if n["author"] == "":
print((Style.BRIGHT +"By: " + src2(temp["name"])) + Style.RESET_ALL)
else:
print((Style.BRIGHT +"By: " + n["author"]) + Style.RESET_ALL)
except:
print((Style.BRIGHT +"By: " + src2(temp["name"])) + Style.RESET_ALL)
try:
print(Back.RED + (Style.BRIGHT + n["title"] + Style.RESET_ALL))
print(Fore.BLUE + n["description"] + Fore.RESET)
except:
print(Fore.RED + "SOME ERROR OCCURED!!!\n" + Fore.RESET)
print(Back.BLUE +(Style.BRIGHT + "url: "+ n["url"]) + Style.RESET_ALL + Back.RESET)
#Similar to author, sometimes the Publishing time is not provided.
#For those cases, there will be no publishing time put. So except case has been made.
try:
print(Fore.GREEN + "Published At: "+ n["publishedAt"] + Fore.RESET )
except:
draw_border()
continue
draw_border()
def category(cat):
url = "https://newsapi.org/v2/top-headlines?category="+ cat +"&language=en&apiKey=" + api_key
try:
with urlopen(url) as httpob:
decob = httpob.read().decode("utf-8")
jsonob = json.loads(decob)
news = jsonob["articles"]
# if api key is Invalid an HTTPError will be thrown.
except HTTPError as e:
print("Invalid API")
create_api_file(file_name)
return console()
# draws a border to seperate posts.
draw_border()
for n in news:
print(Fore.RESET)
temp = n["source"]
print(Back.YELLOW + src2(temp["name"]) + Back.RESET)
try:
if n["author"] == "":
print((Style.BRIGHT +"By: " + src2(temp["name"])) + Style.RESET_ALL)
else:
print((Style.BRIGHT +"By: " + n["author"]) + Style.RESET_ALL)
except:
print((Style.BRIGHT +"By: " + src2(temp["name"])) + Style.RESET_ALL)
try:
print(Back.RED + (Style.BRIGHT + n["title"] + Style.RESET_ALL))
print(Fore.BLUE + n["description"] + Fore.RESET)
except:
print(Fore.RED + "SOME ERROR OCCURED!!!\n" + Fore.RESET)
print(Back.BLUE +(Style.BRIGHT + "url: "+ n["url"]) + Style.RESET_ALL + Back.RESET)
#Similar to author, sometimes the Publishing time is not provided.
#For those cases, there will be no publishing time put. So except case has been made.
try:
print(Fore.GREEN + "Published At: "+ n["publishedAt"] + Fore.RESET )
except:
draw_border()
continue
draw_border()
def good_bye(word, default='has'):
print(Fore.BLUE + Style.BRIGHT +
'*-* Your database {1} been {0}. *-*'.format(word, default))
print(Fore.CYAN + Style.BRIGHT + '*_* Have a nice day! *_*')
sys.exit()
def main():
global log_file
log(Fore.YELLOW, "Loaded {} usernames.".format(len(users)))
log(Fore.YELLOW, "Loaded {} passwords.\n".format(len(passwords)))
log(Fore.BLUE, "Waiting for data from queue...", log_this=False)
log_file = sys.argv[1] if len(sys.argv) >= 2 else "log.txt"
mq_worker()
def Rem(self, arg):
for ID in map(int, arg.split()):
try:
t = _store[ID]
except:
print(_F.RED, 'ID %s Not found' % ID, _S.RESET_ALL, sep='')
else:
r = _root[t.path()[1:]]
r.rem(t)
_tags.rem(t)
_store.release(ID)
print(_F.BLUE, 'Entry removed : \n', str(t), sep='')
def color_diff(diff):
for line in diff:
if line.startswith('+'):
yield Fore.GREEN + line + Fore.RESET
elif line.startswith('-'):
yield Fore.RED + line + Fore.RESET
elif line.startswith('^'):
yield Fore.BLUE + line + Fore.RESET
else:
yield line
def main():
print(Style.BRIGHT + Fore.BLUE + banner + Fore.RESET + Style.RESET_ALL)
try:
os.environ['ANDCRE']
except KeyError:
print(Fore.YELLOW + " ** Important: $ANDCRE environment variable not found ** " + Fore.RESET)
if apply_workspace():
where = input(" [+] Where? ({}): ".format(os.getcwd()))
else:
print(Fore.RED + " [-] Bye bye!\n" + Fore.RESET)
sys.exit()
workspace = set_workspace(where)
print(Fore.GREEN + " [+] Ok! Workspace in '{}' \n".format(workspace) + Fore.RESET)
project_name = set_project_name()
package_name = set_package_name()
abs_project_name = absolute_path_from(os.environ['ANDCRE'], camel_case(project_name))
normalized_package_name = normalize_package_name(package_name)
if check_if_exist_file(abs_project_name):
print(Fore.YELLOW + " [+] Directory '{}' exists, do you want to delete it?".format(abs_project_name)
+ Fore.RESET)
if delete_existing_project():
delete_dir(abs_project_name)
print(Fore.GREEN + " [+] Deleted '{}' folder!\n".format(abs_project_name) + Fore.RESET)
else:
print(Fore.RED + " [-] Don't remove old project, aborting...\n" + Fore.RESET)
sys.exit()
create_dir(abs_project_name)
print(Fore.GREEN + " [+] Created '{}' directory in '{}'".format(project_name, os.environ['ANDCRE']) + Fore.RESET)
project = Project(camel_case(project_name), normalized_package_name, abs_project_name)
project.create_app()
initialize_git_repo(abs_project_name)
print(Fore.GREEN + Style.BRIGHT + " [+] Completed!\n" + Style.RESET_ALL)
def NODE_INFO(IP_ADDR):
resp = urllib2.urlopen("https://onionoo.torproject.org/details?search=%s"%(IP_ADDR))
json_data = resp.read()
data = json.loads(json_data, object_pairs_hook=OrderedDict)
rp = bp = None
colors_lst = [Fore.GREEN + Style.BRIGHT, Fore.RED + Style.BRIGHT, Fore.YELLOW + Style.BRIGHT, Fore.WHITE + Style.BRIGHT, Fore.CYAN + Style.BRIGHT]
for key, value in data.items():
if key == "version" or key == "bridges":
continue
if key == "relays_published":
rp = value
if key == "bridges_published":
bp = value
if key == "relays":
for each in value:
for e_key, e_val in each.items():
#if lists
if e_key == "or_addresses":
print (Fore.GREEN + Style.BRIGHT + e_key.upper() + Fore.WHITE + Style.BRIGHT + " : " + ','.join(e_val))
continue
if e_key.lower() == "exit_policy_summary" or e_key.lower() == "exit_policy" or e_key.lower() == "exit_policy_v6_summary":
continue
if str(e_val).startswith("[") and str(e_val).endswith(']'):
print (Fore.GREEN + Style.BRIGHT + e_key.upper() + Style.RESET_ALL)
for ef in e_val:
print Fore.BLUE + Style.BRIGHT + "\t=> "+ ef + Style.RESET_ALL
continue
try:
print (Fore.GREEN + Style.BRIGHT + e_key.upper().replace('_',' ') + Style.RESET_ALL + " : " + \
Fore.WHITE + Style.BRIGHT + str(e_val))
except: pass
print
if (rp!=None and bp!= None):
print (Fore.GREEN + Style.BRIGHT + "RELAYS PUBLISHED" + Style.RESET_ALL + " : " + Fore.WHITE + Style.BRIGHT + rp)
print (Fore.GREEN + Style.BRIGHT + "BRIDGES PUBLISHED" + Style.RESET_ALL + " : " + Fore.WHITE + Style.BRIGHT + bp)