Esempio n. 1
0
def do_args(arg, quoted_output, output):
  if not quoted_output:
    cmd = '{}://x-callback-url/'.format(arg)
  else:
    if arg == 'onewriter':
      # Replace 'Notepad.txt' with the name of your open doc in 1Writer
      cmd = '{}://x-callback-url/append?path=Documents%2F&name=Notepad.txt&type=Local&text={}'.format(arg, quoted_output)
    if arg == 'editorial':
      clipboard.set(output)
      '''
      'Append Open Doc' is an Editorial workflow
      available here:
      http://www.editorial-workflows.com/workflow/5278032428269568/g2tYM1p0OZ4
      '''
      cmd = '{}://?command=Append%20Open%20Doc'.format(arg)
    if arg == 'drafts4':
      '''
      Append gps data to open Draft doc using the
      2nd argument from calling URL as the UUID of
      the open doc
      '''
      cmd = '{}://x-callback-url/append?uuid={}&text={}'.format(arg, sys.argv[2], quoted_output)

  webbrowser.open(cmd)
  sys.exit('Finished!')
 def copy_action(self, sender):
     file_content = self['file content'].text
     if file_content:
       clipboard.set(file_content)
       console.hud_alert('Copied', 'success', 1.0)
     else:
       console.hud_alert('No text entered to copy.', 'error', 1.0)
Esempio n. 3
0
def main():
	try:
		img.save("pymgur_tmp.png", 'PNG')
	except AttributeError:
		print "There is no image on the clipboard'"
		sys.exit()
	f = open("pymgur_tmp.png", "rb")
	binary_data = f.read()
	b64image = base64.b64encode(binary_data)
	f.close()
	os.remove("pymgur_tmp.png")
	payload = {'key': API_KEY,
	           'image': b64image,
	           'type': 'base64',
	           'title': 'Pymgur Upload {}'.format(datetime.datetime.today().strftime("%c"))
	           }
	print "Uploading..."
	try:
		r = requests.post(url, headers = headers, data = payload)
	except requests.ConnectionError:
		hud_alert('No internet connection', icon = 'error')
		sys.exit()
	j = json.loads(r.text)
	link = j["data"]["link"]
	clipboard.set(link)
	hud_alert('Link Copied!')
	notification.schedule("Pymgur Upload Complete!", delay=0, action_url=link)
	print "The image link ({}) has been copied to the clipboard!".format(link)
Esempio n. 4
0
def _set_clip(str_text, var_ios):
    """Place text in the OSX or iOS clipboard"""

    # If the platform is already known ...
    if var_ios != None:
        bln_ios = var_ios
    else: # otherwise check the platform,
        try:
            import clipboard
            bln_ios = True
        except ImportError:
            import subprocess
            bln_ios = False

    # and set the clipboard accordingly
    if bln_ios:
        import clipboard
        clipboard.set(str_text)
    else:
        import subprocess
        proc = subprocess.Popen(['pbcopy'],
                stdin=subprocess.PIPE)
        proc.stdin.write(str_text)
        proc.stdin.close()
        proc.wait()
def main():
	if not appex.is_running_extension():
		print 'This script is intended to be run from the sharing extension.'
		return
	images = appex.get_attachments('public.jpeg')
	if images:
		a = get_exif(images[0])
		if a.get('GPSInfo'):
			lat = [float(x)/float(y) for x, y in a['GPSInfo'][2]]
			latref = a['GPSInfo'][1]
			lon = [float(x)/float(y) for x, y in a['GPSInfo'][4]]
			lonref = a['GPSInfo'][3]
			lat = lat[0] + lat[1]/60 + lat[2]/3600
			lon = lon[0] + lon[1]/60 + lon[2]/3600
			if latref == 'S':
				lat = -lat
			if lonref == 'W':
				lon = -lon
			loc_str = '%f, %f' % (lat, lon)
			print 'Latitude/Longitude:'
			print loc_str
			clipboard.set(loc_str)
			print '(copied to the clipboard -- you can paste this in the search field of Maps to go to the location where the photo was taken)'
		else:
			print 'No location data found'
	else:
		print 'No input image found'
Esempio n. 6
0
def make_table(fmts, hdrs, vals):
	'''Produce multimarkdown table from python lists of formats, headers,
	and values.
	'''
	# Replace empty headers
	hdrs = [' ' if hdr is None else hdr for hdr in hdrs]
	headers = '|' + '|'.join(hdrs) + '|' + '\n'
	# Construct format list
	fmts_mmd = []
	
	for fmt in fmts:
		if fmt == 'Left':
			fmts_mmd.append(':-')
		elif fmt == 'Right':
			fmts_mmd.append('-:')
		else:
			fmts_mmd.append(':-:')
	
	formats = '|' + '|'.join(fmts_mmd) + '|' + '\n'
	# Replace Nones with empty strings
	nrows = len(vals)
	ncols = len(vals[0])
	values = ''
	
	for i in range(nrows):
		for j in range(ncols):
			if vals[i][j] == None:
				vals[i][j] = ''
		values += '|' + '|'.join(vals[i]) + '|' + '\n'	
	
	table = normtable(headers + formats + values)
	clipboard.set(table)
	
	return table
Esempio n. 7
0
def main ():
    xParser = argparse.ArgumentParser()
    xParser.add_argument("-f", "--file", help="parse file (UTF-8 required!) [on Windows, -f is similar to -ff]", type=str)
    xParser.add_argument("-ff", "--file_to_file", help="parse file (UTF-8 required!) and create a result file (*.res.txt)", type=str)
    xParser.add_argument("-j", "--json", help="generate list of errors in JSON", action="store_true")
    xParser.add_argument("-w", "--width", help="width in characters (40 < width < 200; default: 100)", type=int, choices=range(40,201,10), default=100)
    xParser.add_argument("-tf", "--textformatter", help="auto-format text according to typographical rules", action="store_true")
    xParser.add_argument("-tfo", "--textformatteronly", help="auto-format text and disable grammar checking (only with option 'file' or 'file_to_file')", action="store_true")
    xArgs = xParser.parse_args()

    gce.load()
    gce.setOptions({"html": True})
    oDict = gce.getDictionary()
    oTokenizer = tkz.Tokenizer("fr")
    oLexGraphe = lxg.Lexicographe(oDict)
    if xArgs.textformatter or xArgs.textformatteronly:
        oTF = tf.TextFormatter()

    sText = clipboard.get()
    bDebug = False
    for sParagraph in txt.getParagraph(sText):
        if xArgs.textformatter:
            sText = oTF.formatText(sText)
        sRes = generateText(0, sText, oTokenizer, oDict, xArgs.json, nWidth=xArgs.width, bDebug=bDebug, bEmptyIfNoErrors=True)
        if sRes:
            clipboard.set(sRes)
        else:
            clipboard.set("No errors found.")
    print(sRes)
Esempio n. 8
0
 def copy_code(self, sender):
     if self['txtv'].text:
         code = self.data[self['tv1'].selected_row[0]]
         #clipboard.set(self['txtv'].text)
         clipboard.set(code)
         console.hud_alert('Copied', duration = .5)
         self.close()
Esempio n. 9
0
def main():
	global b64str
	cpimage = clipboard.get_image()
	#if image was in clipboard.
	if cpimage:
		#resize to icon size.
		icon = cpimage.resize((57, 57), Image.BILINEAR)
		#convert to rgb format.
		icon = icon.convert('RGB')
#		icon.show()	#show resized image.
		#create string buffer to write png file to.
		iconstr = StringIO()
		#write image to string buffer in png format.
		icon.save(iconstr, 'png')
		#convert save buffer to base64.
		b64str = base64.standard_b64encode(iconstr.getvalue())
		#put base64 string in clipboard.
		clipboard.set(b64str)
	
	#now decode to test.	
	mystr = base64.standard_b64decode(b64str)
	#read file from string buffer.
	stb = StringIO(mystr)
	img = Image.open(stb)
	#show the image.
	img.show()
	#print some info.
	print str(img.format)
	print str(img.mode)
	print str(img.size)
	print str(img.info)
Esempio n. 10
0
def main():
	filename = editor.get_path()
	if not filename:
		dialogs.hud_alert('No file selected', 'error')
		return
	pyui_filename = os.path.splitext(filename)[0] + '.pyui'
	if not os.path.exists(pyui_filename):
		folder = os.path.split(filename)[0]
		files = os.listdir(folder)
		files = [f for f in files if f.endswith('.pyui')]
		if not files:
			dialogs.hud_alert('No pyui files found', 'error')
			return
		selected_pyui = dialogs.list_dialog('Select pyui file', files)
		if not selected_pyui:
			return
		pyui_filename = os.path.join(folder, selected_pyui)
	with open(pyui_filename, 'rb') as f:
		pyui = f.read()
	compressed = base64.b64encode(bz2.compress(pyui)).decode('utf-8')
	wrapped = '\n'.join(textwrap.wrap(compressed, 70))
	code = """\
data = '''\\\n%s
'''
import ui
import bz2
from base64 import b64decode
pyui = bz2.decompress(b64decode(data))
v = ui.load_view_str(pyui.decode('utf-8'))
""" % (wrapped,)
	clipboard.set(code)
	dialogs.hud_alert('Code copied', 'success')
Esempio n. 11
0
def copy_action(sender):
    '@type sender: ui.Button'
    t1 = sender.superview['label1'].text
    t2 = sender.superview['label2'].text
    text = t2 + ' ' + t1 if t2 else t1
    clipboard.set(text)
    hud_alert('Copied')
Esempio n. 12
0
def copy_lido_route(action_in, params):
    """
    Copy the Lido route into the clipboard
    :param action_in: the input passed to the action
    :param params: the workflow parameters for the action

    Usage from Editorial is:

    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    import workflow
    from editolido.workflows.lido2mapsme import copy_lido_route


    params = workflow.get_parameters()
    action_in = workflow.get_input()
    workflow.set_output(copy_lido_route(action_in, params))

    """
    from editolido.ofp import OFP
    import clipboard  # EDITORIAL Module
    import console  # EDITORIAL Module

    if params['Copier']:
        ofp = OFP(action_in)
        clipboard.set(' '.join(ofp.lido_route))
        if params['Durée'] > 0 and params['Notification']:
            console.hud_alert(params['Notification'], 'success',
                              float(params['Durée']))
    return action_in
Esempio n. 13
0
 def cut(self):
     import clipboard
     i=editor.get_selection()
     t=editor.get_text()
     clipboard.set(t[i[0]:i[1]])
     editor.replace_text(i[0],i[1], '')
     editor.set_selection(i[0],i[0])
Esempio n. 14
0
def out_to_clipboard(sender):
	request = post_multipart("c.docverter.com", "/convert", formats.items() + fields, files)
	buffer = StringIO.StringIO(request)
	output = buffer.getvalue()
	clipboard.set(output)
	buffer.close()
	view.close()
	workflow.stop()
def main():
    try:
        choice = console.alert("Copy what?", "Choose...", "File (full)", "File (~/Documents)", "Dir")
    except:
        choice = 1
    fn = editor.get_path()
    fn = fn[fn.find("/Documents"):] if choice == 2 else os.path.split(fn)[0][8:] if choice == 3 else fn[8:]
    clipboard.set(fn)
Esempio n. 16
0
def action(sender):
    clipboard.set(_btns[sender.title])
    sender.superview.close()
    console.hud_alert('Copied', duration = .4)

    # print to the console, if in debug mode
    if _debug_mode:
        print _btns[sender.title]
 def anchor(self, sender):
     templ = " <a name='#'></a>"
     (start, end) = self.markup.selected_range
     link_label = self.markup.text[start:end]
     link_name = quote(self.markup.text[start:end])
     templ = templ.replace("#", link_name)
     self.markup.replace_range((end, end), templ)
     link = "[" + link_label + "](#" + link_name + ")"
     clipboard.set(link)
Esempio n. 18
0
def main():
	text = ''
	with codecs.open('LinkStack.txt', 'r', 'utf-8') as f:
		for line in f:
			text += CreateLink.main(line[:-1]) + '\n'
	clipboard.set(text)
	console.alert('Link Created!', '', 'OK', hide_cancel_button=True)
	with codecs.open('LinkStack.txt', 'w', 'utf-8') as f:
		f.write('')
def button_tapped(sender):
    prefix = 'You chose: '
    if not sender.title.startswith(prefix):
        clipboard.set(sender.title)
        sender.font = ('<system-bold>', 16)
        sender.title = prefix + sender.title
        buttons_disable()
        sender.enabled = True
    else:
        clipboard.set(sender.title[len(prefix):])
Esempio n. 20
0
def copy_action(sender):
    "@type sender: ui.Button"
    t1 = sender.superview["label1"].text
    t2 = sender.superview["label2"].text
    if t2:
        text = t2 + " " + t1
    else:
        text = t1
    clipboard.set(text)
    hud_alert("Copied")
Esempio n. 21
0
def alt(comic):
    if not comic: return
    ans = console.alert('{month}/{day}/{year}'.format(**comic), comic['alt'], 'Copy link', 'Explain')
    if ans == 1:
        #dialogs.share_url('http://xkcd.com/{}/'.format(sender.superview.current))
        clipboard.set('http://xkcd.com/{}/'.format(comic['num']))
        console.hud_alert('Copied!')
    elif ans == 2:
        explain_view.load_url('http://www.explainxkcd.com/wiki/index.php/{}'.format(comic['num']))
        nav.push_view(explain_view)
Esempio n. 22
0
def shorten_with_isgd(long_url):
  '''basic link-shortening via is.gd.'''
  api_base_url = 'http://is.gd/create.php?format=simple&url={url}'
  try:
    response = urlopen(api_url_base.formtat(url=long_url))
  except IOError:
    error_dialog('Connection Error', 'Unable to perform request.')
  if response.getcode() == 200:
    short_link = response.read()
	clipboard.set(short_link)
Esempio n. 23
0
def main():
    
    # get text from app share or clipboard
    if appex.is_running_extension():
        text = appex.get_url()
    else:
        text = clipboard.get().strip()

    # get url
    url = ''
    try:
        url = [ mgroups[0] for mgroups in GRUBER_URLINTEXT_PAT.findall(text) ][0]
    except:
        url = console.input_alert("URL", "", url)
    if url:
        if not 'http' in url:
            url = 'http://' + url
    else:
        console.hud_alert('No URL found.')
        sys.exit()

    sel = console.alert('Save: %s ?' % url, button1='File', button2='Clipboard')

    # get url info
    url_items = url.split("?")[0].split("/")
    # if url ends with /, last item is an empty string
    file_name = url_items[-1] if url_items[-1] else url_items[-2]
    try:
        content = urllib2.urlopen(url).read()
    except Exception as e:
        console.alert(e.message)
        sys.exit()

    if sel == 1:
        # get file save info
        save_dir_name = get_save_dir()
        save_dir = os.path.join(BASE_DIR, save_dir_name)
        file_path = os.path.join(save_dir, file_name)
        try:
            # check dirs and save
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)
            with open(file_path, 'w') as f:
                f.write(content)
                f.close()
            # wrapup
            console.alert('Saved to: %s' % file_path, hide_cancel_button=True, button1='OK')
        except Exception as e:
            console.alert(str(e), button1='OK',hide_cancel_button=True)
    elif sel == 2:
        clipboard.set(content)


    if appex.is_running_extension():
        appex.finish()
Esempio n. 24
0
 def do_it(self):
     text = self['text_view'].text.rstrip()
     if text:
         lang = 'python' if self['python_code'].value else ''
         text = fmt.format(lang, text)
         clipboard.set(text)
         self['text_view'].text = text
         console.hud_alert('The post is now on your clipboard.')
         print(text)
     else:
         print('No user text.')
Esempio n. 25
0
def save(icon_label, flow_name):
	port = 8000
	flow = '"'+flow_name+'"'
	flow = flow.replace('"','%22')
	flow = flow.replace(' ','%20')
	#urllib.parse.urlencode('"'+flow_name+'"')
	
	clipboard.set('http://127.0.0.1:%s/webclip.mobileconfig' % port)
	console.alert(title='Message', message='If safari doesn\'t open, open Safari and paste url in clipboard to url and install profile',button1='Ok',hide_cancel_button=True)
	webbrowser.open('safari-http://127.0.0.1:%s/webclip.mobileconfig' % port)
	serve_it_up(port, icon_label, flow)
Esempio n. 26
0
def main(args):
    ap = argparse.ArgumentParser()
    ap.add_argument('file', nargs='*', help='one or more files to be copied')
    ns = ap.parse_args(args)
    
    fileinput.close() # in case it is not closed
    try:
        clipboard.set(''.join(line for line in fileinput.input(ns.file, openhook=fileinput.hook_encoded("utf-8"))))
    except Exception as err:
        print("pbcopy: {}: {!s}".format(type(err).__name__, err), file=sys.stderr)
    finally:
        fileinput.close()
Esempio n. 27
0
def main():
    song_page = None
    if (len(sys.argv) > 0):
        try:
            song_page = sys.argv[1]
        except Exception:
            song_page = None
    if not song_page:
        print repr(sys.argv)
        return
    console.clear()
    
    # kopiert den Namen der Datei in die zwischenablage
    console.show_activity()
    soup = bs4.BeautifulSoup(urllib.urlopen(song_page))
    pageTitle = soup.title.string
    console.hide_activity()
    console.clear()
    clipboard.set(pageTitle)
    print pageTitle
    
    
    print "Grabbing:", song_page
    sess = requests.Session()
    sess.headers.update({'User-Agent': 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5'})
    print " .. getting xtsite and js .. "
    find_xtsite_js = sess.get(song_page).text
    xtsite = find_xtsite_js.rsplit('xtsite',1)[1].split(';',1)[0].split('"',1)[1].split('"',1)[0]
    the_js = find_xtsite_js.rsplit('m-a.sndcdn.com',1)[1].split('"',1)[0].split('/')[-1]
    print " .. getting client_id .. "
    new_headers = {'Accept-Encoding': 'identity', 'Connection': 'close'}
    sess.headers.update(new_headers)
    find_client_id = sess.get('http://m-a.sndcdn.com/' + the_js)
    client_id = find_client_id.content[:250].split('clientId',1)[1].split(';',1)[0].split('"',1)[1].split('"',1)[0]
    print "id:", client_id
    today = datetime.datetime.utcnow().now()
    # ---- cookies here ----
    xtant='1'
    xtan='-'
    xtvrn='$'+xtsite+'$'
    xtidc = today.strftime('%y') + ('%02d' % (today.month-1)) + today.strftime('%d%H%M%S') + str(random.randint(10000,999999))
    sc_anonymous_id = '-'.join([str(random.randint(10000,999999)) for x in range(4)])
    # ---- end cookies ----
    sess.headers.update({'X-Requested-With': 'XMLHttpRequest'})
    new_cookies = {'xtant': xtant, 'xtan': xtan, 'xtvrn': xtvrn, 'xtidc': xtidc, 'sc_anonymous_id': sc_anonymous_id}
    print " .. getting track id .. "
    find_track_id = sess.get('http://m.soundcloud.com/_api/resolve?url=%s&client_id=%s&format=json' % (song_page, client_id), cookies = new_cookies, allow_redirects=False).headers['location']
    track_id = find_track_id.split('.json',1)[0].rsplit('/',1)[-1]
    print "id:", track_id
    mp3_url = 'http://api.soundcloud.com/tracks/%s/stream?client_id=%s' % (track_id, client_id)
    download_url = mp3_url.replace('http://', 'ghttp://')
    webbrowser.open(download_url)
	def snippetselectaction(self, snippet):
		selection = dialogs.alert(title='Action', message='Please select your action', button1='Copy to clipboard', button2='Create new file', button3='Show/Edit Snippet contents')
		if selection == 1:
			clipboard.set(snippet[2])
		elif selection == 2:
			title = dialogs.input_alert(title='Filename Entry', message='Please enter a title for your new file, to insert in a folder foldername\filename.py')
			self.make_file(filename=title, contents=snippet[2])
		elif selection == 3:
			dialogs.alert(title='Message',message='Press\nDone - to save content changes \nX - to cancel and not save', button1='Ok', hide_cancel_button=True)
			contents = dialogs.text_dialog(title=snippet[1], text=snippet[2])
			if not contents == None:
				dbmanager().edit_snippet(contents = contents, title=snippet[1], snippetid=snippet[0])
				self.updatesnippetslistview()
Esempio n. 29
0
def main():
    post_file = clipboard.get()
	
    markdownified = markdown.markdown(post_file)

    links_fixed = fix_links(markdownified)
    
    code_fixed = fix_code(links_fixed)

    final_text = code_fixed

    clipboard.set( unicode(final_text) )
    webbrowser.open('wordpress://')
 def do_hash_generation(self, location, prev_location, timestamp):
     if self.count < 999:
         self.hash.update('{}{}{}{:15f}'.format(location[0],location[1],prev_location,timestamp))
         self.count += 3
         self.name = str(
                         float(self.count)/10
                         ) + '% complete'
         self.textview.text = 'Hash: ' + self.hash.hexdigest() #show the text in the textview
     elif self.count == 999:
         self.name = str(100.0) + '% complete'
         print self.hash.hexdigest()
         clipboard.set(self.hash.hexdigest())
         self.close() #close the view
Esempio n. 31
0
sc2.action = seg2_selected

dp = v['datepicker1']
lbl = v['label1']

# Sync label display with date picker
lbl.text = change_date(dp)

# Display ui locked in portrait orientation and wait till user closes view via 'Done' button
v.present(orientations = ['portrait'], hide_title_bar = True)
v.wait_modal()

date_time = lbl.text

# Send date_time text to clipboard
clipboard.set('')
clipboard.set(date_time)
'''
Allow to run script stand alone or from another
app using command line arguments via URL's.
'''
try:
  # No error if this script was called from a app using URL
  app = sys.argv[1]
  
  # Append date-time text to a 1Writer doc named 'Notepad.txt' stored locally.
  if app == 'onewriter':
    import urllib
    quoted_output = urllib.quote(date_time, safe = '')
    cmd = 'onewriter://x-callback-url/append?path=/Documents%2F&name=Notepad.txt&type=Local&text={}'.format(quoted_output)
  elif app == 'drafts4':
Esempio n. 32
0
import sys
import clipboard

path = os.getcwd()
files = []
for item in sorted(os.listdir(path)):
    if '.pyui' in item:
        print item,
        files.append(item)
print
print
if len(files) == 1:
    filename = raw_input('Please choose pyui file or press return for [' +
                         files[0] + ']: ') or files[0]
elif len(files) > 1:
    filename = raw_input('Please choose pyui file: ')
else:
    print 'Sorry no pyui file found!'
    sys.exit()

if not '.pyui' in filename:
    filename += '.pyui'

if os.path.exists(filename):
    path += '/' + filename
    file = open(path, 'r')
    clipboard.set(file.read())
    file.close()
    print filename + ' is in clipboard.'
else:
    print "Can't find " + filename
Esempio n. 33
0
script_name = console.input_alert('Script path')
arg_str = console.input_alert('Script arguments')
payload_name = 'Pythonista Script'

console.alert('Please select an icon', '', 'Ok')
png_data = StringIO()
photos.pick_image().save(png_data, format='PNG')
png_str = base64.b64encode(png_data.getvalue())
png_data.close()

UUID1 = uuid.uuid4()
UUID2 = uuid.uuid4()

mobile_config_str = base_mobileconfig % (png_str, icon_label, UUID1, UUID1, urllib.quote(script_name), arg_str, payload_name, UUID2, script_name, UUID2)

clipboard.set('http://%s:%s/webclip.mobileconfig' % (ip, port))

console.clear()
console.set_font('Futura', 16)
console.set_color(0.2, 0.2, 1)
print "Safari will open automatically. Alternatively, you can open Safari manually and paste in the URL on your clipboard.\n"
console.set_font()
console.set_color()

my_httpd = NicerHTTPServer((ip, port), MobileConfigHTTPRequestHandler)
print "Serving HTTP on %s:%s ..." % (ip, port)

webbrowser.open('safari-http://%s:%s/webclip.mobileconfig' % (ip, port))
my_httpd.serve_forever()

print "\n*** Webclip installed! ***"
Esempio n. 34
0
other_clouds = [
    (datetime.fromtimestamp(hour['time']).hour,
     str(round(hour['cloudCover'] * 100)) + "%")
    for hour in [i for i in day_after_conditions['hourly']['data']]
    if hour['time'] in remaining_hours and hour['cloudCover'] <= 0.1
]

for other_cloud in other_clouds:
    cloud_list.append(other_cloud)

output = ""
if len(cloud_list) == 0:
    output = "No, the skies are far too cloudy tomorrow. Try again the next day."
else:
    output += "Yes, you can observe tomorrow. "
    for tupl in cloud_list:
        if tupl[0] > 12:
            output += f"Cloud cover is {tupl[1]} at {tupl[0] % 12} PM. "
        elif tupl[0] == 0:
            output += f"Cloud cover is {tupl[1]} at 12 AM. "
        else:
            output += f"Cloud cover is {tupl[1]} at {tupl[0]} AM. "
    output += f"Sunset tomorrow is at {datetime.fromtimestamp(sunset).hour}:{sunset_min} PM. "
    output += moon_phase
    output += f"Moon presence is at {round(curr_conditions['daily']['data'][0]['moonPhase']*100)}%. "
    output += f"Sunrise is at {datetime.fromtimestamp(sunrise).hour}:{sunrise_min} AM on the following day."

clipboard.set('{}'.format(output))
url = "shortcuts://"
webbrowser.open(url)
Esempio n. 35
0
import clipboard
import xml.dom.minidom

xml = xml.dom.minidom.parse('./result.xml') # or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = xml.toprettyxml()

clipboard.set(pretty_xml_as_string)
Esempio n. 36
0
 def cb_info_button(self, sender, text):
     # the listpanel calling us with the text from the ui.TableView
     quote = "'"
     clipboard.set('{quote}{item}{quote}'.format(item=text, quote=quote))
     console.hud_alert(text + '-Copied')
     self.close()
Esempio n. 37
0
'''
	
file_path = editor.get_path()
file_name = os.path.basename(file_path)
file_dir = os.path.dirname(file_path)
name, suffix = os.path.splitext(file_name)

target_dir = os.path.join(file_dir, _notes_sub_dir)
target_file = os.path.join(target_dir, '{}.{}'.format(name, _notes_suffix))

if _copy_to_clip:
	# get the selected text in the file, if any
	sel = editor.get_selection()
	selection_text = editor.get_text()[sel[0]:sel[1]]
	if selection_text:
		clipboard.set(selection_text)
		
if not os.path.exists(target_dir):
	os.mkdir(target_dir)
	
if not os.path.exists(target_file):
	'''
		not using editor.make_new_file() here as far as i know you cant control how it opens.
		it opens replacing the current tab, instead of opening in a new tab
		
	'''
	creation_date_str = datetime.datetime.now().strftime(_creation_date_str)
	with open(target_file, 'w') as f:
		f.writelines(_file_header_text.format(src_name=file_name,
												 src_path=file_path,
												 creation_date=creation_date_str,
Esempio n. 38
0
disk1_id = d["DISKID"]
print "disk from image created"

print "creating swap disk"
d = linode.linode_disk_create(LinodeID=node_id,
                              Label="swap disk",
                              Type="swap",
                              size=DISK_SWAP_SIZE)
disk2_id = d["DiskID"]
print "swap disk created"

print "creating config"
disk_list = "{},{}".format(disk1_id, disk2_id)
linode.linode_config_create(LinodeID=node_id,
                            KernelID=kernel_id,
                            Label="tvdev config",
                            DiskList=disk_list)
print "config created"

print "booting node"
linode.linode_boot(LinodeID=node_id)

print "retrieving IPs"
ips = linode.linode_ip_list(LinodeID=node_id)
ip = ips[0]["IPADDRESS"]
clipboard.set(ip)
print "IP address {} copied to clipboard".format(ip)

if return_url != None:
    webbrowser.open(return_url)
import clipboard

filename = "put_your_filename_here.pyui"  # edit this line before running
with open(filename) as in_file:
    clipboard.set(in_file.read())
print("The contents of {} are now on the clipboard.".format(filename))
Esempio n. 40
0
campaign = console.input_alert("",
                               "Enter campaign flag for affiliate tracking.",
                               "&ct=twitter", "Groovey")

# Get the URL from the clipboard.
clipURL = clipboard.get()

# Add myID and the partnerId parameter to the URL. If there are already
# queries, add them as additional ones; if not, add them as the only ones.
if '?' in clipURL:
    itemURL = '%s&at=%s%s' % (clipURL, myID, campaign)
else:
    itemURL = '%s?at=%s%s' % (clipURL, myID, campaign)

# Write to console
# console.clear()
# stdout.write(itemURL)

# Copy to clipboard
#clipboard.set(itemURL)

s = urllib.parse.quote(itemURL.encode('utf-8'))
t = urllib.parse.quote(tweetText.encode('utf-8'))

openLink = 'tweetbot://therotcod/post?text=' + t + '%0A%0A' + s

clipboard.set(itemURL)

webbrowser.open(openLink)
# coding: utf-8
import clipboard, base64, console, appex

etext = clipboard.get()
if 'base64,' in etext:
    etext = etext.split('base64,')[1]
text = base64.decodestring(etext)
try:
    clipboard.set(text)
    if not appex.is_running_extension():
        print text
    console.hud_alert('Clipboard base64 decoded.')
except:
    console.hud_alert('Error base64 decoding clipboard.')
Esempio n. 42
0
songlist.append("45. Free Bird - Lynyrd Skynyrd")
songlist.append("46. She Sells Sanctuary - The Cult")
songlist.append("47. Whiskey in the Jar - Thin Lizzy")
songlist.append("48. Run Like Hell - Pink Floyd")
songlist.append("49. In These Arms - Bon Jovi")
songlist.append("50. Lazy Sunday Afternoon - Thunder")
songlist.append("51. Pinball Wizard - The Who")
songlist.append("52. Ships in the Night - Be Bop Deluxe")
songlist.append("53. Born to be Wild - Steppenwolf")
songlist.append("54. Enter Sandman - Metallica")
songlist.append("55. Rock and Roll - Led Zeppelin")
songlist.append("56. Livin' On A Prayer - Bon Jovi")
songlist.append("57. Runaway - Bon Jovi")
songlist.append("58. In A Broken Dream - Thunder")
songlist.append("59. Bohemian Rhapsody - Queen")
songlist.append("60. St. Elmos Fire - John Parr")
# songlist.append("53. Little Devil - The Cult")
# songlist.append("54. 747 Strangers in the Night - Saxon")
# songlist.append("55. Can’t Get Enough - Bad Company")
# songlist.append("56. Paranoid - Black Sabbath")
# songlist.append("57. Ain’t No Talking Bout Love - Van Halen")
# songlist.append("58. Feel Like Making Love - Bad Company")
# songlist.append("59. Ziggy Stardust - David Bowie")
# songlist.append("60. Over the Hills n Far Away - Gary Moore")
# songlist.append("61. Perfect Strangers - Deep Purple")
# songlist.append("62. Kayleigh and Lavender - Marrilion")
# songlist.append("63. Hotel California - The Eagles")
# songlist.append("64. November Rain - GnR")

clipboard.set(str(random.sample(songlist, 1)))
Esempio n. 43
0
    if w > 620:
        wsize = 620 / float(w)
        print('wsize: ' + str(wsize))
        hsize = int(float(h) * float(wsize))
        print('hsize: ' + str(hsize))

        img = img.resize((620, hsize), Image.ANTIALIAS)
    return img


image = customSize(image)
print(image.size)
image.show()

buffer = BytesIO()
image.save(buffer, 'PNG')
buffer.seek(0)

print(remoteFilePath)
print(fileName)

fileURL = urllib.quote(fileName)

ftp = ftplib.FTP(host, userName, userPass)
ftp.cwd(remoteFilePath)
ftp.storbinary('STOR ' + fileName, buffer)
ftp.quit()
imageLink = urlBase + fileURL
print(imageLink)
clipboard.set(imageLink)
Esempio n. 44
0
import keychain
import clipboard
import console
import webbrowser

instance_id = "i-123456ab"
key = "ABCDEFGHIJKLMNOPQRST"

return_url = None
if len(sys.argv) >= 2:
    return_url = sys.argv[1]

secret = keychain.get_password("aws", key)
if secret == None:
    secret = console.password_alert("Enter secret key")
    keychain.set_password("aws", key, secret)

print "Connecting"
ec2_conn = boto.connect_ec2(aws_access_key_id=key,
                            aws_secret_access_key=secret)

print "Stopping instance"
ec2_conn.stop_instances(instance_ids=[instance_id])

msg = "Shutdown in progress"
clipboard.set(msg)
print msg

if return_url != None:
    webbrowser.open(return_url)
Esempio n. 45
0
# coding: utf-8

# Captured from: _https://forum.omz-software.com/topic/2506/possible-to-share-pyui-files_

print open('Test.pyui').read()

###==============================

import clipboard

with open("thing.pyui") as f:
    clipboard.set(f.read())
def serve_it_up(port):
    global mobile_config_str
    global base_mobileconfig
    ip = '127.0.0.1'
    icon_label = 'pyClock'
    UUID1 = str(uuid.uuid4()).upper()
    script_name = 'Clock'
    arg_str = ''
    payload_name = 'Pythonista - %s' % script_name
    UUID2 = str(uuid.uuid4()).upper()
    mobile_config_str = base_mobileconfig % (icon_label, UUID1, UUID1,
                                             script_name, arg_str,
                                             payload_name, UUID2, UUID2)
    my_httpd = NicerHTTPServer((ip, port), MobileConfigHTTPRequestHandler)
    print "Serving HTTP on %s:%s ..." % (ip, port)
    my_httpd.serve_forever()
    print "\n*** Webclip installed! ***"


port = 8000
clipboard.set('http://127.0.0.1:%s/webclip.mobileconfig' % port)
console.clear()
console.set_font('Futura', 22)
console.set_color(0.2, 0.2, 0.2)
print "Open Safari and paste in the URL on your clipboard\n"
console.set_color(0.9, 0.2, 0.2)
print "It will pause loading,\n   then re-open Pythonista!\n"
console.set_font()
console.set_color()
serve_it_up(port)
Esempio n. 47
0
    def touch_began(self, touch):

        current = location.get_location()
        latLong = (round(current['latitude'],4), round(current['longitude'],4)) #solved the close points problem using rounding
        picTaken = latLong in self.photoLocations


        x,y = touch.location

        if self.loopPrompt == True:
            if x > 50 and x < self.size.x/2 and y < self.size.y/2 and y > self.size.y/2 - 50:
                self.loopPrompt = False
                self.loopPromptState = 1
            elif x > self.size.x/2 and x < self.size.x-50 and y < self.size.y/2 and y > self.size.y/2 - 50:
                self.loopPrompt = False
                self.loopPromptState = 2

        elif self.MoreState == True:
            #SOS State
            if x < self.size.w/2 + 30 and x > self.size.w/2 - 30 and y > 50 and y < 100 and self.MoreState == True:
                webbrowser.open('tel:911')

            #MapView
            elif x < 100 and x > 50 and y < 220 and y > 160 and len(self.locations) >= 2:
                googleMapsMaxPoints = 20
                mapLocations = copy.deepcopy(self.locations)
                if len(self.locations) > googleMapsMaxPoints:
                    mapLocations = []
                    jump = math.ceil(len(self.locations)/googleMapsMaxPoints)
                    for i in range(0,len(self.locations),jump):
                        mapLocations += [self.locations[i]]
                self.query = 'safari-https://www.google.com/maps/dir/'
                for loc in mapLocations:
                    self.query += str(loc[0])
                    self.query += ","
                    self.query += str(loc[1])
                    self.query += "/"
                self.query = self.query[:-1]
                webbrowser.open(self.query)

            elif x < self.size.x/2+40 and x > self.size.x/2-40 and y < 220 and y > 160 and len(self.locations) >= 2:
                googleMapsMaxPoints = 20
                mapLocations = copy.deepcopy(self.locations)
                if len(self.locations) > googleMapsMaxPoints:
                    mapLocations = []
                    jump = math.ceil(len(self.locations)/googleMapsMaxPoints)
                    for i in range(0,len(self.locations),jump):
                        mapLocations += [self.locations[i]]
                self.query = 'safari-https://www.google.com/maps/dir/'
                for loc in mapLocations:
                    self.query += str(loc[0])
                    self.query += ","
                    self.query += str(loc[1])
                    self.query += "/"
                self.query = self.query[:-1]
                clipboard.set(self.query[7:])
                self.clipState = True


            elif x < self.size.x-50 and x > self.size.x-100 and y < 220 and y > 160:
                self.pathState = True

            else:
                self.MoreState = False
                self.clipState = False
                self.pathState = False

        #open landmark
        elif y > 150 and y < 200 and self.imageMode == True:
            sound.play_effect('arcade:Laser_2')
            self.imageModeOpen = True
            self.imageMode = False











        #reset button
        elif x < 100 and x > 50 and y < 100 and y > 50:
            self.measuringOn = False
            self.checkedOnce = 0
            self.background_color = 'white'
            self.locations = []
            self.needMore = False
            self.photoCount = 0
            self.photoLocations = []
            self.locationsLeft = []
            self.needMore = False
            self.timerCount = 0


        #more button
        elif x < self.size.w/2 + 25 and x > self.size.w/2 - 25 and y < 30 and y > 0:
            self.MoreState = True

        #take photos and add to album
        elif x < self.size.w/2 + 30 and x > self.size.w/2 - 30 and y > 50 and y < 100 and self.MoreState == False and self.measuringOn == True and picTaken == False:
            imageree = photos.capture_image()
            if imageree != None:
                photos.save_image(imageree)
                time.sleep(1)
                self.photoCount += 1
                allAssets = photos.get_assets()
                theImage = allAssets[-1]
                #print("Divider")
                # Find the album or create it:
                try:
                    self.photoLibrary = [a for a in photos.get_albums() if a.title == 'Thread'][0]
                except IndexError:
                    self.photoLibrary = photos.create_album('Thread')
                # Add the file as an asset to the library:
                # asset = photos.create_image_asset(theImage)
                # Add the asset to the album:
                theImage = allAssets[len(allAssets)-1]
                self.photoLibrary.add_assets([theImage])

                current = location.get_location()
                latLongPic = (round(current['latitude'],4), round(current['longitude'],4)) #solved the close points problem using rounding
                self.photoLocations += [latLongPic]









        #compass State: Letters (NWSE) or degrees
        elif x < 325 and x > 275 and y < 100 and y > 50:
            self.compassStat = not(self.compassStat)

        elif self.measuringOn == False and self.checkedOnce == 0:
            #sound.play_effect('arcade:Laser_2')
            self.measuringOn = True
            self.background_color = 'white'
            self.checkedOnce += 1

        elif self.measuringOn == True and self.checkedOnce == 1 and len(self.locations) < 4:
            #sound.play_effect('arcade:Laser_1')
            self.needMore = True

        elif self.measuringOn == True and self.checkedOnce == 1 and len(self.locations) > 3:
            #sound.play_effect('arcade:Laser_1')
            self.needMore = False
            self.measuringOn = False
            self.background_color = 'white'
            self.checkedOnce += 1

        elif self.measuringOn == False and self.checkedOnce == 3:
            #sound.play_effect('arcade:Laser_1')
            self.background_color = 'white'
            self.checkedOnce += 1
Esempio n. 48
0
# coding: utf-8
import base64
import clipboard
import appex

source = appex.get_text()
if source == None:
    source = clipboard.get()

encoded = base64.b64encode(source)
print(encoded)
clipboard.set(encoded)
Esempio n. 49
0
# https://gist.github.com/viticci/b27acfeb04c25101e4ea

from bs4 import BeautifulSoup
import urllib2
import appex
import dialogs
import clipboard

channel = appex.get_url()
webpage = urllib2.urlopen(channel)
soup = parser(webpage)

feeds = soup.findAll("link", rel="alternate")
for RSS_link in feeds:
    url = RSS_link.get("href", None)
    if 'feeds' in url:
        dialogs.alert('Found Channel RSS', url, 'Copy')
        clipboard.set(url)
Esempio n. 50
0
# Taken from Viticci :: https://github.com/viticci/pythonista-scripts
# Uses direct link to image in clipboard to generate HTML code suitable for MacStories
# Should work just about anywhere else though.
# Please note: script will ask for image Title and Alt attributes using an input_alert from console.

import clipboard
import console

image = clipboard.get()

alts = console.input_alert("Image Alt", "Type alt below")
title = console.input_alert("Image Title", "Type title below")

final = "<img src=" + '"' + image + '"' + " " + "alt=" + '"' + alts + '"' + " " + "title=" + '"' + title + '"' + " " + "class=\"aligncenter\" />"

print final
clipboard.set(final)
Esempio n. 51
0
# into the clipboard.
#
# It will also, depending on the argument passed to it, launch any of the actions defined.
#
# (c) 2014 Dexter Ang. MIT License.
#

import clipboard
import sys
import urllib
import webbrowser

my_ip = urllib.urlopen("http://ifconfig.me/ip")
my_ip_string = my_ip.read()

clipboard.set(my_ip_string)

argument = sys.argv

if len(argument) == 2:
  if argument[1] == "1":
    # Drafts
    webbrowser.open("drafts4://x-callback-url/create?text=" + urllib.quote(my_ip_string))
  elif argument[1] == "2":
    # iMessage
    webbrowser.open("launch://messaging?body=" + urllib.quote(my_ip_string))
  elif argument[1] == "3":
    # Email
    webbrowser.open("launch://email?subject=" + urllib.quote("My IP address") + "&body=" + urllib.quote(my_ip_string))
  elif argument[1] == "4":
    # Gmail
Esempio n. 52
0
def setClip(data):
    clipboard.set(data)
Esempio n. 53
0
def main(ref):
    # Converts Unicode to String
    ref = ref.encode()
    # Proper case
    ref = ref.title()

    user_input = 'Verse(s): {}'.format(ref)
    '''
  Allow to run script stand alone or from another
  app using command line arguments via URL's.
  '''
    try:
        app = sys.argv[1]
    except IndexError:
        app = ''

    # Make list to spit multiple passages into
    fulltext = []

    # List of Bible versions available in the api
    versions = 'akjv asv basicenglish darby kjv wb web ylt'.split()

    # Pick your desired Bible version by number
    #0 = akjv...KJV Easy Read
    #1 = asv...American Standard Version
    #2 = basicenglish...Basic English Bible
    #3 = darby...Darby
    #4 = kjv...King James Version
    #5 = wb...Webster's Bible
    #6 = web...World English Bible
    #7 = ylt...Young's Literal Translation

    # Change number to match desired version
    version = versions[0]
    the_refs = parse_refs(ref)

    for r in the_refs:
        book = r.get('book')
        chapter = r.get('chapter')
        verses = r.get('verses')

        # Check syntax of book for spelling & spacing errors
        book, chapter = check_book(book, chapter)

        # For debug...
        #print 'book: ' + book
        #print 'chapter: ' + str(chapter)
        #print 'verses: ' + str(verses)
        #print 'first verse: ' + first_verse
        #print 'last verse: ' + last_verse

        if chapter and verses:
            ref = '{} {}:{}'.format(book, chapter, verses)
            type = 'verse'
        if chapter and not verses:
            ref = '{} {}'.format(book, chapter)
            type = 'chapter'
        if not chapter and not verses:
            ref = '{}'.format(book)
            type = 'book'

        # Debug
        #print ref
        #print type
        #sys.exit()

        # Query passage
        console.hud_alert('Querying For {}...'.format(ref))
        p = passage_as_dict(ref, version)

        err_msg = 'No scripture found for "{}"...Check syntax.'.format(ref)

        # If query returned scripture...
        if p != 'NULL':
            # Pretty up query results
            if type == 'book':
                t = book_only(p)
            if type == 'chapter':
                t = book_chapter(p)
            if type == 'verse':
                t = book_chapter_verses(p, verses)
        else:
            t = err_msg

        # Converts list to string
        t = '\n'.join(t)

        # Add markdown syntax to highlight verse ref
        t = '**{} ({})**\n{}'.format(ref, version.upper(), t)
        # Add scripture to list
        fulltext.append(t)

    # Converts list to string
    fulltext = '\n\n'.join(fulltext)
    # Prepend verses and line feeds to scripture
    #fulltext = '{}\n\n{}'.format(user_input, fulltext)
    fulltext = fulltext.encode()
    # Uncomment to debug
    #print fulltext

    # Return scripture to caller app, if any
    if app:
        url = get_url(app, fulltext)
        webbrowser.open(url)
        sys.exit('Query results exported to {}.'.format(app))
    else:
        # Clear clipboard, then add formatted text
        clipboard.set('')
        clipboard.set(fulltext)
        fulltext = ('''
The results of the scripture query are
shown below and copied to the clipboard
for pasting into the MD text editor or
journaling app of your choice.\n\n''') + fulltext
        #print fulltext
        # Check if MarkdownView module is available and go with TextView if necessary.
        try:
            import MarkdownView as mv
            md = mv.MarkdownView()
        except ImportError:
            import ui
            md = ui.TextView()
        md.background_color = 'orange'
        md.font = ('<system-bold>', 14)
        md.text = fulltext
        md.editable = False
        md.present()
Esempio n. 54
0
# -*- coding: utf-8 -*-

# To call script, use the follwing URL Action:
# - <pythonista://insert_location.py?action=run&argv=nav>

import location
import urllib
import webbrowser
import time
import clipboard

location.start_updates()
time.sleep(1)
b = location.get_location()
location.stop_updates()

b = str(b["latitude"]) + "," + str(b["longitude"]) + ","

clipboard.set(b)

webbrowser.open("launch://x-callback-url/")
Esempio n. 55
0
#!python3

# Fahrenheit to Celsius is (F – 32) * 5/9 = C

import sys
import console
import clipboard
import webbrowser

fahrenheit = float(sys.argv[1])
celsius = (fahrenheit - 32) * 5 / 9

clipboard.set("{0:.1f}⁰ F = {1:.1f}⁰ C".format(fahrenheit, celsius))
webbrowser.open('workflow://')
Esempio n. 56
0
def copy_action(sender):
    import clipboard
    clipboard.set(editor_view.text)
    import console
    console.hud_alert('Copied')
Esempio n. 57
0
    def touch_began(self, touch):
        sound.play_effect('Footstep')

        #creates a query of the locations recorded and opens it on google maps
        #because the query accepts at most around 20 points, if you have more
        #than 20 points it will create a new list and get points evenly spaced
        #throughout the path to a total of less than 20. Looks representative
        #and accurate.
        def mapView(self):
            googleMapsMaxPoints = 20
            mapLocations = copy.deepcopy(self.locations)
            if len(self.locations) > googleMapsMaxPoints:
                mapLocations = []
                jump = math.ceil(len(self.locations) / googleMapsMaxPoints)
                for i in range(0, len(self.locations), jump):
                    mapLocations += [self.locations[i]]
            self.query = 'safari-https://www.google.com/maps/dir/'
            for loc in mapLocations:
                self.query += str(loc[0])
                self.query += ","
                self.query += str(loc[1])
                self.query += "/"
            self.query = self.query[:-1]
            webbrowser.open(self.query)

        #when you run across a landmark (photo) you placed down, it will
        #notify you its present and you can tap to reveal the photo
        def openLandmark(self):
            sound.play_effect('Click_1')
            self.imageModeOpen = True
            self.imageMode = False

            self.heightPhoto = (self.photoHeight/self.photoWidth) * \
            (self.size.x-20)
            self.widthPhoto = (self.photoWidth/self.photoWidth) * \
            (self.size.x-20)

            self.heightFrame = self.heightPhoto + 10
            self.widthFrame = self.widthPhoto + 10

            self.halfScreenFrame = self.size.y / 2 - self.heightFrame / 2
            self.halfScreen = self.size.y / 2 - self.heightPhoto / 2

            #asked a question on the omz (Pythonista) forum and they answered!
            #'https://forum.omz-software.com/topic/5263/displaying-an-image-
            #from-album-in-photos-onto-screen-in-scene-module'
            #opens the image and has it hidden.
            self.img = ui.Button(name='image')
            self.img.frame = (10, self.halfScreen, self.widthPhoto,
                              self.heightPhoto)
            self.img.background_image = self.ui_image
            self.img.enable = False
            self.img.hidden = False
            self.view.add_subview(self.img)

        #when you tap, get the current location to perform functions
        current = location.get_location()
        #solved the close points problem using rounding
        latLong = (round(current['latitude'],
                         4), round(current['longitude'], 4))
        picTaken = latLong in self.photoLocations

        #get the location on the screen of the touch
        x, y = touch.location

        #if the image is open, close it when you tap (has to be off the image)
        if self.imageModeOpen == True:
            self.imageModeOpen = False
            self.img.hidden = True

        #if you have the loop Prompt, you must tap an answer in order to use
        #the other functions
        if self.loopPrompt == True:
            if x > 50 and x < self.size.x/2 and y < self.size.y/2 \
            and y > self.size.y/2 - 50:
                self.loopPrompt = False
                self.loopPromptState = 1
            elif x > self.size.x/2 and x < self.size.x-50 \
            and y < self.size.y/2 and y > self.size.y/2 - 50:
                self.loopPrompt = False
                self.loopPromptState = 2

        #when it has the more menu open, you must are not able to tap any of
        #the other buttons, other than the ones in the more menu
        elif self.MoreState == True:
            #SOS State tap, call the cops if you tap
            if x < self.size.w/2 + 30 and x > self.size.w/2 - 30 \
            and y > 50 and y < 100 and self.MoreState == True:
                webbrowser.open('tel:911')

            #MapView tap
            elif x < 100 and x > 50 and y < 220 and y > 160 and \
            len(self.locations) >= 2:
                mapView(self)

            #create the query, but make it a link for phone users, and copy
            #it to the clipboard
            elif x < self.size.x/2+40 and x > self.size.x/2-40 and \
            y < 220 and y > 160 and len(self.locations) >= 2:
                googleMapsMaxPoints = 20
                mapLocations = copy.deepcopy(self.locations)
                if len(self.locations) > googleMapsMaxPoints:
                    mapLocations = []
                    jump = math.ceil(len(self.locations) / googleMapsMaxPoints)
                    for i in range(0, len(self.locations), jump):
                        mapLocations += [self.locations[i]]
                self.query = 'safari-https://www.google.com/maps/dir/'
                for loc in mapLocations:
                    self.query += str(loc[0])
                    self.query += ","
                    self.query += str(loc[1])
                    self.query += "/"
                self.query = self.query[:-1]
                clipboard.set(self.query[7:])
                self.clipState = True

            #tap on Trace button to reveal the path
            elif x < self.size.x-50 and x > self.size.x-100 and y < 220 \
            and y > 160 and len(self.locations) > 2:
                self.pathState = True

            #tap on theme button to switch the theme
            elif x < self.size.w/2 + 30 and x > self.size.w/2 - 30 \
            and y > self.size.y-95-40 and y < self.size.y-95+40:
                self.themeSwitch += 1
                if self.themeSwitch % 2 == 0:
                    self.theme = self.lightMode
                elif self.themeSwitch % 2 == 1:
                    self.theme = self.darkMode

            #tap off a button while in the more menu, and it exits the menu
            else:
                self.MoreState = False
                self.clipState = False
                self.pathState = False

        #open landmark by tapping on the banner
        elif y > 150 and y < 200 and self.imageMode == True:
            openLandmark(self)

        #if in image mode, tap off the image to get rid of it off the screen
        elif y < 150 and y > 200 and self.imageMode == True:
            self.imageMode = False

        #reset button resets everything
        elif x < 100 and x > 50 and y < 100 and y > 50:
            self.measuringOn = False
            self.functionState = 0
            self.background_color = self.theme["backgroundColor"]
            self.locations = []
            self.needMore = False
            self.photoCount = 0
            self.photoLocations = []
            self.locationsLeft = []
            self.needMore = False
            self.timerCount = 0

        #more button is a small and out of the way, opens up more menu
        elif x < self.size.w/2 + 25 and x > self.size.w/2 - 25 and y < 30 \
        and y > 0:
            self.MoreState = True

        #take photos and add to album
        elif x < self.size.w/2 + 30 and x > self.size.w/2 - 30 \
        and y > 50 and y < 100 and self.MoreState == False and \
        self.measuringOn == True and picTaken == False:
            imageree = photos.capture_image()
            if imageree != None:
                #open up the camera and you can take photo
                photos.save_image(imageree)
                time.sleep(1)
                self.photoCount += 1
                allAssets = photos.get_assets()
                theImage = allAssets[-1]
                #if there is no album, create album 'Thread'
                try:
                    self.photoLibrary = [a for a in photos.get_albums() \
                    if a.title == 'Thread'][0]
                except IndexError:
                    self.photoLibrary = photos.create_album('Thread')

                #add the image to the album for the user to have and for
                #future use in the app's use (landmarks!)
                theImage = allAssets[len(allAssets) - 1]
                self.photoLibrary.add_assets([theImage])

                self.photoLocations += [latLong]

        #compass State: Letters (NWSE) or degrees
        elif x < 325 and x > 275 and y < 100 and y > 50:
            self.compassStat = not (self.compassStat)

        #go to measuring mode when tapped for the first time
        elif self.measuringOn == False and self.functionState == 0:
            self.measuringOn = True
            self.background_color = self.theme["backgroundColor"]
            self.functionState += 1

        #if you need more values do not let the user stop recording
        elif self.measuringOn == True and self.functionState == 1 \
        and len(self.locations) < 4:
            self.needMore = True

        #if you have enough locations, when you tap you can move to next state
        elif self.measuringOn == True and self.functionState == 1 \
        and len(self.locations) > 3:
            #sound.play_effect('arcade:Laser_1')
            self.needMore = False
            self.measuringOn = False
            self.background_color = self.theme["backgroundColor"]
            self.functionState += 1

        #move function state up to state 4 so you can begin tracing back
        elif self.measuringOn == False and self.functionState == 3:
            #sound.play_effect('arcade:Laser_1')
            self.background_color = self.theme["backgroundColor"]
            self.functionState += 1
Esempio n. 58
0
import urllib
import clipboard
import bs4
import webbrowser
import console

link = clipboard.get()

soup = bs4.BeautifulSoup(urllib.urlopen(link))
clipboard.set(soup.title.string + ' ' + link)
text = clipboard.get()
console.clear()
print(text)
Esempio n. 59
0
 def run(self, input):
     clipboard.set(input.value)
     self.status = 'complete'
Esempio n. 60
0
# -*- coding: utf-8 -*-

import clipboard
import webbrowser

clipboard.set('')
webbrowser.open('workflow://')