Esempio n. 1
0
def main():
    if appex.is_running_extension():
        if appex.get_url():
            text = appex.get_url()
        else:
            text = appex.get_text()
    else:
        text = clipboard.get()
    if not text:
        text = console.input_alert('Jira ID')

    if text:
        ids = JIRA_PAT.findall(text)
        if len(ids) == 0:
            text = console.input_alert('Jira ID')
        ids = JIRA_PAT.findall(text)
        if len(ids) > 0:
            id = ids[0]
            base_url, username = get_conf_info()
            url = '%s/browse/%s' % (base_url, id)
            console.hud_alert('Jira ID: %s' % id)
            app=UIApplication.sharedApplication()
            url=nsurl(url)
            app.openURL_(url)
        else:
            console.hud_alert('No Jira ID found.')
    else:
        console.hud_alert('No input text found.')
    if appex.is_running_extension():
        appex.finish()
def preptext():
  # Prepare content in clipboard

  # Get Clipboard
  clip = clipboard.get()
  
  print('\n(1) Preparing Text\n -Retrieved Clipboard: '+clip)
  	
  # Collect / validate desc and URL w/ user
  url = console.input_alert("URL?","",clip,"OK")
  
  desc = console.input_alert("Commentary?","","","OK")
  
  # Prepare URL
  if (len(url) < 1):
  	  ## Set the URL / title to empty
    finalurl, shorturl, title = ''
  	
  else:
    # Follow URL to final destination
    
    req = urllib2.Request(url,None,hdr)
    
    try: 
      res = urllib2.urlopen(req)
      finalurl = res.geturl()
    except urllib2.HTTPError, e:
      print 'HTTPError = ' + str(e.code)
    except urllib2.URLError, e:
      print 'URLError = ' + str(e.reason)
	def tableview_did_select(self, tableview, section, row):
		param = self.params[row]
		name = param.displayName
		value = param.value
		if name == None or name == '':
			name = param.name
		if value == None:
			value = ''
		if param.type == 'string':
			param.value = console.input_alert(name, '', value)
		elif param.type == 'int':
			param.value = int(console.input_alert(name,'',str(value)))
		elif param.type == 'variable':
			pass
		elif param.type == 'list':
			ret = dialogs.list_dialog(title=name,items=param.allowedValues, multiple=param.multipleAllowed)
			yo = ''
			if not ret == None:
				if isinstance(ret,list):
					for item in ret:
						yo += item+','
				else:
					yo = ret
				yo = yo.rstrip(',')
			param.value = yo
		elif param.type == 'dictionary':
			self.dictionaryParam = param
			self.dictView = ElementParameterDictionaryInputView.get_view(dictionary=param.value, title=name, cb=self.dictionaryReturn, thememanager = self.thememanager)
			self.tv = tableview
			self.dictView.title_bar_color = self.thememanager.main_bar_colour
			self.dictView.tint_color = self.thememanager.main_tint_colour
			self.dictView.present(orientations=['portrait'])
		tableview.reload()
Esempio n. 4
0
def main():
	console.alert('Shortcut Generator', 'This script adds a "Webclip" shortcut to your homescreen. The shortcut can be used to open a web page in full-screen mode, or to launch a custom URL (e.g. a third-party app). You\'ll be asked for a title, a URL, and an icon (from your camera roll).', 'Continue')
	label = console.input_alert('Shortcut Title', 'Please enter a short title for the homescreen icon.', '', 'Continue')
	if not label:
		return
	url = console.input_alert('Shortcut URL', 'Please enter the full URL that the shortcut should launch.', '', 'Continue')
	if not url:
		return
	icon = photos.pick_image()
	if not icon:
		return
	console.show_activity('Preparing Configuration profile...')
	data_buffer = BytesIO()
	icon.save(data_buffer, 'PNG')
	icon_data = data_buffer.getvalue()
	unique_id = uuid.uuid4().urn[9:].upper()
	config = {'PayloadContent': [{'FullScreen': True,
            'Icon': plistlib.Data(icon_data), 'IsRemovable': True,
            'Label': label, 'PayloadDescription': 'Configures Web Clip', 
            'PayloadDisplayName': label,
            'PayloadIdentifier': 'com.omz-software.shortcut.' + unique_id, 
            'PayloadOrganization': 'omz:software', 
            'PayloadType': 'com.apple.webClip.managed',
            'PayloadUUID': unique_id, 'PayloadVersion': 1,
            'Precomposed': True, 'URL': url}], 
            'PayloadDescription': label,
            'PayloadDisplayName': label + ' (Shortcut)', 
            'PayloadIdentifier': 'com.omz-software.shortcut.' + unique_id,
            'PayloadOrganization': 'omz:software', 
            'PayloadRemovalDisallowed': False, 'PayloadType': 
            'Configuration', 'PayloadUUID': unique_id, 'PayloadVersion': 1}
	console.hide_activity()
	run_server(config)
Esempio n. 5
0
	def tableview_did_select(self, tableview, section, row):
		param = self.params[row]
		name = param.displayName
		value = param.value
		noVariable = True
		if param.isVariableAllowed:
			choice = console.alert(title='Variable Available', message = 'Would you like to choose a variable?', button1='Choose Variable', button2 = 'Ask when run', button3='Don\'t use a variable')
			if choice == 1:
				noVariable = False
				param.useVariable = True
				param.variableName = console.input_alert(title='Option',message='Please enter the variable name')
				param.value = None
				param.askAtRuntime = False
			elif choice == 2:
				noVariable = False
				param.useVariable = True
				param.value = None
				param.askAtRuntime = True
				param.variableName=''
			else:
				noVariable = True
				param.useVariable = False
				param.askAtRuntime = False
				param.variableName = ''
		if name == None or name == '':
			name = param.name
		if value == None:
			value = ''
		if noVariable and param.type == 'string':
			param.value = console.input_alert(name, '', value)
		elif noVariable and param.type == 'int':
			param.value = int(console.input_alert(name,'',str(value)))
		elif noVariable and param.type == 'variable':
			pass
		elif noVariable and param.type == 'list':
			ret = dialogs.list_dialog(title=name,items=param.allowedValues, multiple=param.multipleAllowed)
			yo = ''
			if not ret == None:
				if isinstance(ret,list):
					for item in ret:
						yo += item+','
				else:
					yo = ret
				yo = yo.rstrip(',')
			param.value = yo
		elif noVariable and param.type == 'dictionary':
			self.dictionaryParam = param
			self.dictView = ElementParameterDictionaryInputView.get_view(dictionary=param.value, title=name, cb=self.dictionaryReturn, thememanager = self.thememanager)
			self.tv = tableview
			self.dictView.title_bar_color = self.thememanager.main_bar_colour
			self.dictView.tint_color = self.thememanager.main_tint_colour
			self.dictView.present(orientations=['portrait'])
		elif noVariable and param.type == 'Boolean':
			pass
		tableview.reload()
def fileManagerButtonPressed(_self, _cmd):
	path = console.input_alert('File Copier')
	try:
		file = open(path, 'r')
		content = file.read()
		file.close()
		path = console.input_alert('Paste Path')
		file = open(path, 'w')
		file.write(content)
		file.close()
	except IOError:
		console.alert('Error', 'Path not found')
Esempio n. 7
0
def main():
    if appex.is_running_extension():
        url = appex.get_url()
    else:
        url = clipboard.get().strip()
        if not RE_URL.match(url):
            try:
                url = console.input_alert("Enter gamefaqs URL", "", "https://www.gamefaqs.com/")
            except KeyboardInterrupt:
                sys.exit(0)
    
    newurl = "{0}?print=1".format(url)
    #baseurl = http://www.gamefaqs.com/ps3/959558-fallout-new-vegas/faqs/61226
    if RE_URL.match(url):
        h = html2text.HTML2Text()
        r = requests.get(
                         url=newurl, 
                         headers={"User-agent": "Mozilla/5.0{0:06}".format(random.randrange(999999))}
                         )
        html_content = r.text.decode('utf-8')
        rendered_content = html2text.html2text(html_content)
        filename = url.partition("gamefaqs.com/")[-1].partition("/")[-1].partition("/faqs")[0]+".txt"
        filepath = os.path.join(os.path.expanduser("~/Documents"), filename)
        
        with open(filepath, "w") as fo:
            fo.write(rendered_content)
        
        console.hud_alert('Success! Saved {0}'.format(filename), "success")
def main():
  console.clear()
  
  print("---- Getting Started ----")
  
  # Collect / prepare text
  url, shorturl, title, desc = preptext()
  
  # Prompt with current content: post / edit / cancel
  preview = console.alert("Preview",desc+" - "+shorturl,"Post","Edit")
  
  if (preview == 2):
    ## Edit
    ### Prompt to edit remaining text (if any)
    desc = console.input_alert("Adjust Message","Edit to suit.",desc,"Post","OK")
  
  # Verify where to send messages
  target = console.alert("Where to?","Options:","All","Hipchat")
  
  # Distribute posts
  if (target == 1):
    post_twitter(desc,shorturl)
    post_slack_api(desc,shorturl)
    print "(6) Sending to all channels."
  else:
  	  print "(6) Sending just to Hipchat."
  
  # Use _api for direct posts and _app to load the local iOS app
  post_hipchat_api(desc,shorturl)
  #post_hipchat_app(desc,shorturl)
  #dropbox_write(desc,url,shorturl,title)

  # Display results in console
  print("\n---- All Finished! ----")
Esempio n. 9
0
 def invoke(self, sender):
     print sender
     try:
         c = console.alert("New", "File/Folder", "File", "Folder") - 1
         #print c
         r = console.input_alert("New File", "Enter Filename")
         #print "%r" % r
         if c == 0:
             if r.endswith(".html"):
                 self.tableview_data[c][r] = templates.HTML.format(r)
             elif r.endswith(".css"):
                 self.tableview_data[c][r] = templates.CSS
             elif r.endswith(".js"):
                 try:
                     text = templates.JAVASCRIPT.format(r)
                 except KeyError as e:
                     text = templates.JAVASCRIPT.replace("{}",r)
                 self.tableview_data[c][r] = text
             elif r.endswith("_handler.py"):
                 self.tableview_data[c][r] = templates.REQUEST_HANDLER
             else:
                 self.tableview_data[c][r] = "Hello World from %r" % r
         elif c == 1:
             self.tableview_data[c][r] = [{}, {}]
         #print self.tableview_data[c][r]
         self.fileManager.save_data()
     except KeyboardInterrupt:
         print "The user cancled the input"
     self.tableview.reload_data()
Esempio n. 10
0
	def new_keymap(self):
		"""creates a new keymap."""
		try:
			keymapname = console.input_alert(
				"Create new Keymap",
				"Please enter the name of the new Keymap.",
				"",
				"Create"
				)
		except KeyboardInterrupt:
			return
		if len(keymapname) == 0 or keymapname == MSG_NEW_KEYMAP:
			console.alert(
				"Please enter a name for the Keymap!",
				"",
				"Ok",
				hide_cancel_button=True
				)
			return
		if keymapname in os.listdir(KEYMAPPATH):
			console.alert(
				"Error",
				"A Keymap with this name already exists!",
				"Ok",
				hide_cancel_button=True
				)
			return
		keymap = Keymap(keymapname, {})
		self.edit_keymap(keymap)
Esempio n. 11
0
def pick_your_weather():
  city = country = id = ''
  lat = lon = 0

  # Pick a weather source
  try:
    ans=console.alert('Choose Your Weather Source:','','From Your Current Location','From Entering a City Name','From A Pick List of Cities')
    if ans==1:
      # Weather where you are
      print 'Gathering weather data from where you are...'
      # Get lat & lon of where you are
      lat,lon=get_current_lat_lon()
    elif ans==2:
      # Enter a city & country
      msg='Enter a city and country in format "'"New York, US"'": '
      ans=console.input_alert(msg).title()
      if ans:
        print('='*20)
        print 'Gathering weather data for '+ans
        city=ans.replace(' ','+')
    elif ans==3:
      # Pick from list
      theCity,country,id=city_ids()
      print('='*20)
      if id:
        print 'Gathering weather data for '+theCity+', '+country
  except Exception as e:
    sys.exit('Error: {}'.format(e))

  # Call api from www.openweathermap.org
  w,f=get_weather_dicts(lat,lon,city,id)
  return w,f
Esempio n. 12
0
 def wrapper(sender):
     appname = console.input_alert("Enter application's name")
     if appname:
         if appname in table.data_source.items:
             return error("App already in list")
         apps[appname] = []
         table.data_source.items.append(appname)
Esempio n. 13
0
	def run(self, input=''):
		np = self.get_param_by_name('VariableName')
		name = np.value or console.input_alert('Please enter Variable name')
		rv = self.get_param_by_name('fm:runtime_variables')
		if not name in rv.value:
			rv.value[name] = None
		if rv.value[name] == None:
			rv.value[name] = input.copyMe()
			rv.value[name].value = []
			rv.value[name].value.append(input.copyValue())
			#if not input.objcCopy:
			#	rv.value[name] = copy.deepcopy(input)
			#else:
			#	ev = ElementValue(input.type, input.value.copy(), input.isList, )
			#	rv.value[name] = ev
		else:
			if input.type == rv.value[name].type:
				if not isinstance(rv.value[name].value,list):
					#t = copy.deepcopy(rv.value[name].value)
					t = rv.value[name].copyValue()
					rv.value[name].value = []
					rv.value[name].value.append(t)
					
				if isinstance(input,list):
					
					for i in input.copyValue():
						rv.value[name].value.append(i)
				else:
					rv.value[name].value.append(input.copyValue())
			else:
				console.alert('Error','Incorrect type to append to variable',button1='Ok',hide_cancel_button=True)
				
		self.status = 'complete'
Esempio n. 14
0
def onSave(button):
	global nodeDelegate,walker,undoStack,fileDirectory
	try:
		fileName = console.input_alert('Ouptut File','Enter Output File Name',fileDirectory+'/')
	except KeyboardInterrupt:
		return
	
	base,ext = os.path.splitext(fileName)
	if not ext:
		ext = '.pyui'
		
	if ext not in ['.pyui','.json']:
		console.hud_alert('invalid ui file type')
		return

	root = nodeDelegate.items[0]['node']
	
	fileName = base+ext
	
	rowByUUID = {}
	for row,item in enumerate(nodeDelegate.items):
		rowByUUID[item['node']['uuid']] = row
		
	pyui = pyuiBuilder(rowByUUID,nodeDelegate)
	outString = pyui.makeString(root)
	
	with open(fileName, 'wb') as fh:
		fh.write(outString)
Esempio n. 15
0
 def wrapper(sender):
     ext = console.input_alert("Enter extension")
     if ext:
         if not ext.startswith("."):
             ext = "." + ext
         apps[appname].append(ext)
         table.data_source.items.append(ext)
Esempio n. 16
0
def get_args(argv):
  args = { 'action': 'set_password',
             'user': None,
             'text': clipboard.get(),
             'date': date.today().strftime('%Y%m%d'),
        'overwrite': "0" }
  for a in argv:
    pairs = a.split(':')
    for p in pairs:
      (k, v) = p.split('=', 2)
      if k not in args:
        raise ValueError("Invalid argument '%s'" % (k))
      args[k] = v

  if args['user'] is None:
    args['user'] = console.input_alert("Tradervue Username")
  if not re.match(r'^\d{8}$', args['date']):
    raise ValueError("Invalid date format '%s'. Must be YYYYMMDD" % (args['date']))

  if int(args['overwrite']) == 0:
    args['overwrite'] = False
  else:
    args['overwrite'] = True

  args['date'] = datetime.strptime(args['date'], '%Y%m%d')

  return args
Esempio n. 17
0
	def run(self, input=''):
		output = None
		while output == None or not output.isdigit():
			output = console.input_alert(title='Input', message='Please enter a valid number')
		output = float(output)
		self.status = 'complete'
		return ElementValue(type = self.get_output_type(), value = output)
Esempio n. 18
0
def commit():
	token = get_token()
	fpath = editor.get_path()
	fname = os.path.basename(fpath)
	m = console.input_alert('Edit Description','Enter a new description:','')
	if m == '': m = None
	gist_id = get_gist_id()
	res = commit_or_create(gist_id,{fpath:editor.get_text()},token,m)
	try:
		id = res['id']
	except KeyError:
		if gist_id:
			f = console.alert('Commit Failed',
			'Do you have permission to commit? Would you like to fork?','Fork')
			if f == 1:
				res = fork(gist_id,token)
				try:
					id = res['id']
				except KeyError:
					console.alert('Fork Error', 'There was a problem with the fork')
				else:
					set_gist_id(id)
					res = commit_or_create(id,{fpath:editor.get_text()},token,m)
					try:
						id = res['id']
					except KeyError:
						console.alert('Commit Error',
						'Commit still failed, maybe fork too')
	else:
		if gist_id is None:
			set_gist_id(id)
	print('success!')
Esempio n. 19
0
def add_feed(sender):
	url = console.input_alert('', "Enter RSS feed URL:", 'http://www.macstories.net/feed/')
	result = urlparse.urlparse(url)
	if result.netloc == '':
		url = 'http://www.macstories.net/feed/'

	indicator = ui.ActivityIndicator()
	indicator.center = navigation_view.center
	navigation_view.add_subview(indicator)
	indicator.bring_to_front()
	indicator.start()

	feed = feedparser.parse(url)
	title = feed['feed']['title']

	conn = sqlite3.connect('feeds.db')
	conn.execute('INSERT INTO feeds VALUES (?, ?)', (title, url))
	conn.commit()

	feeds = []
	for title, url in conn.execute('SELECT * FROM feeds ORDER BY title'):
		feeds.append({'title': title, 'url': url })

	conn.close()

	feed_list_controller.feeds = feeds
	table_view.reload()
	indicator.stop()
	navigation_view.remove_subview(indicator)
Esempio n. 20
0
def pick_your_weather():
  city = st = zcode = ''
  lat = lon = 0

  # Pick a weather source
  try:
    ans = console.alert('Choose Your Weather Source:', '', 'From Your Current Location', 'From Entering a City Name', 'From A Pick List of Cities')
    if ans == 1:
      # Weather where you are
      print 'Gathering weather data from where you are...'
      # Get lat & lon of where you are
      lat, lon = get_current_lat_lon()
    elif ans == 2:
      # Enter a state-country & city
      msg = 'Enter a city and state-country in format "'"New York, NY"'": '
      ans = console.input_alert(msg).title()
      if ans:
        print('='*20)
        print 'Gathering weather data for {}'.format(ans)
        ans = ans.split(',')
        city = ans[0].replace(' ', '%20').strip()
        st = ans[1].strip()
    elif ans == 3:
      # Pick from list
      theCity, st, zcode = city_zips()
      print('='*20)
      if zcode:
        print 'Gathering weather data for {}, {}'.format(theCity, st)
  except Exception as e:
    sys.exit('Error: {}'.format(e))

  # Call api from www.wunderground.com
  w, f = get_weather_dicts(lat, lon, city, st, zcode)
  return w, f
Esempio n. 21
0
def set():
	gist = get_gist_id(editor.get_path())
	if gist == None: gist = ''
	gist = console.input_alert('Assign Gist ID','Enter the gist id for this file',gist)
	try:
		set_gist_id(editor.get_path(),gist)
	except InvalidGistIDError:
		console.alert('Invalid Gist ID', 'That does not appear to be a valid gist id')
def fileExplorerButtonPressed(_self, _cmd):
	path = console.input_alert('File Explorer')
	try:
		files = os.listdir(path)
		sfiles = "\n".join(files)
		console.alert(path, sfiles)
	except OSError:
		console.alert('Error', 'Path not found')
Esempio n. 23
0
def new_md(sender):
    filename = console.input_alert('', 'File Name')
    if filename.find('.')>-1:
        filename = filename[:filename.rfind('.')]
    filename += '.md'
    fh = open(filename, 'a')
    del fh
    editor.open_file(filename)
def fileManagerButtonPressed(_self, _cmd):
	path = console.input_alert('File Reader')
	try:
		file = open(path, 'r')
		console.alert(path, file.read())
		file.close()
		#console.quicklook(path)
	except IOError:
		console.alert('Error', 'Path not found')
Esempio n. 25
0
 def run(self, input):
     np = self.get_param_by_name("VariableName")
     if np.value == None:
         name = console.input_alert("Please enter Variable name")
     else:
         name = np.value
     rv = self.get_param_by_name("fm:runtime_variables")
     rv.value[name] = copy.deepcopy(input)
     self.status = "complete"
Esempio n. 26
0
 def wrapper(sender):
     ext = console.input_alert("Enter extension")
     if ext:
         if not ext.startswith("."):
             ext = "." + ext
         if ext in table.data_source.items:
             return error("Extensions already in list")
         apps[appname].append(ext)
         table.data_source.items.append(ext)
Esempio n. 27
0
def WC_callback_key(overwrite_key=False):
    service = "Working Copy"
    # UUID appended to avoid collision with another script
    # (generated on original dev machine)
    account = "x_callback_url_6653ee08-4c43-4453-a400-c5de315b0725"
    key = keychain.get_password(service, account)
    if overwrite_key or not key:
        key = console.input_alert("Enter Working Copy URL key:")
        keychain.set_password(service, account, key)
    return key
Esempio n. 28
0
def WorkPic(img):
	titles = console.input_alert('Image Upload', 'Enter your image name below')
	console.show_activity()
	buffer = BytesIO()
	img.save(buffer, 'JPEG', quality=100)
	buffer.seek(0)
	imgname = today.strftime("%Y-%m-%d-at-%H-%M-%S") + '-' + titles + '.jpeg'
	response = dropbox_client.put_file('/MacStories_Team/Photos/Ticci/upload-unedited/' + imgname, buffer)
	console.hide_activity()
	print 'Image Uploaded'
Esempio n. 29
0
	def run(self):
		np = self.get_param_by_name('VariableName')
		rv = self.get_param_by_name('fm:runtime_variables')
		keysavailablestring = ''
		for k in rv.value:
			keysavailablestring += k + ' '
		keysavailablemessage = 'Keys to choose from are: ' + keysavailablestring
		if (np.value or '').replace(' ', '') == '':
			try:
				key = dialogs.list_dialog('Vars',list(rv.value.keys()))
				self.name = key
			except :
				# if dialogs isnt available then fall back to console input
				self.name = console.input_alert(title='Please enter variable title', message=keysavailablemessage)
				
		else:
			self.name = np.value
		self.name = self.name or console.input_alert(title='Please enter variable title', message=keysavailablemessage)
		return rv.value[self.name].copyMe()
Esempio n. 30
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. 31
0
# Will prompt a URL to grab gist files, it will pre-populate with current clipboard contents.
# You can also just enter the gist ID by itself.
# Will write each file by its filename

import sys
import requests
import os
import console
import clipboard
import json


def codeget(url):
    r = requests.get('https://api.github.com/gists/%s' %
                     os.path.split(url.strip().split(" ")[0])[-1])
    f = json.loads(r.text)
    for x, v in f['files'].iteritems():
        with open(v['filename'], 'w') as ip:
            ip.write(v['content'])
            print 'Wrote %d chars to %s' % (len(v['content']), v['filename'])


if __name__ == '__main__':
    a = console.input_alert('URL', 'Enter URL', clipboard.get())
    codeget(a)
Esempio n. 32
0
	console.show_activity()
	
	url = clipboard.get()
	
	soup = bs4.BeautifulSoup(urllib.urlopen(url))
	newlink = (soup.title.string + ' ' + url).encode('utf-8')
	
	console.hide_activity()
	
else:

	title = sys.argv[1]
	url = sys.argv[2]
	newlink = title + ' ' + url
	
newtask = console.input_alert('What is this?', 'Type your reminder below')

newtime = console.input_alert('When?', '3600 for 1 hour, 1800 for 30 minutes')

console.hide_activity()

text = newtask + ' - ' + newlink

encoded = urllib.quote(text, safe='')

err_handler = '&x-source=Source%20App&x-error=pythonista://&x-success=' + url

openDue = addnew + encoded + addtime + newtime + err_handler

console.clear()
Esempio n. 33
0
	
	soup = bs4.BeautifulSoup(urllib.urlopen(url))
	title = soup.title.string
	text = title.encode('utf-8')
	
	console.hide_activity()
	
else:

	text = sys.argv[1]
	url = sys.argv[2]
	
PASSWORD = '******'
USER = '******'

tags = console.input_alert('Tags', 'Enter your tags below')

console.show_activity()

query = {'url': url,
         'description': text,
         'tags': tags}
query_string = urlencode(query)

pinboard_url = 'https://api.pinboard.in/v1/posts/add?' + query_string

r = requests.get(pinboard_url, auth=(USER, PASSWORD))

console.clear()

if r.status_code != 200:
Esempio n. 34
0
# Very simple SSH client for Pythonista
import paramiko
import console

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
host = console.input_alert('Connect to')
user, passwd = console.login_alert('Login')
ssh.connect(host, username=user, password=passwd)
print 'Connected to %s. Type `exit` to disconnect.' % host
while True:
    cmd = raw_input()
    if cmd == 'exit':
        break
    stdin, stdout, stderr = ssh.exec_command(cmd)
    print stdout.read()
ssh.close()
print 'Disconnected.'
Esempio n. 35
0
# Motion control demo
from scene import *
#from math import sin,pi
import time
import console
from board import *
import sys

hole = 7
kb = 0
forward = False
if len(sys.argv) > 1:
    hole = int(sys.argv[1])
console.clear()
hole = console.input_alert("Golf Tee Game", "Enter an open hole (1-15)", "1")
hole = int(hole) - 1
filled = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
filled[hole] = 0
boards = doit(filled)
boards.reverse()
#print(boards)
xc = list(range(0, 15))
yc = list(range(0, 15))
scale = 600
size = 50
tnow = time.time()
tswipe = 0.0
tmove = 1.5
global ot
ot = True
Esempio n. 36
0
 def _javascript_prompt(self, host, prompt, default_text):
     try:
         return console.input_alert(host, prompt, default_text, 'OK')
     except KeyboardInterrupt:
         return None
Esempio n. 37
0
def set():
	gist = get_gist_id(editor.get_path())
	if gist == None: gist = ''
	gist = console.input_alert('Assign Gist ID','Enter the gist id for this file',gist)
	set_gist_id(editor.get_path(),gist)
Esempio n. 38
0
import re

import requests
import json
import base64

SITE_BRANCH = 'gh-pages' # either master or gh-pages

#keychain.delete_password('GitHub', 'username')
#keychain.delete_password('GitHub', 'token')
#keychain.delete_password('GitHub', 'repository')

# Get Username, API Token and Repository
username = keychain.get_password('GitHub', 'username')
if not username:
	username = console.input_alert("Username", "Enter your GitHub Username", '', "Save")
	keychain.set_password('GitHub', 'username', username)
	
tokn = keychain.get_password('GitHub', 'token')
if not tokn:
	tokn = console.password_alert("API Token", "Enter your GitHub API Token", '', "Save")
	keychain.set_password('GitHub', 'token', tokn)

repo = keychain.get_password('GitHub', 'repository')
if not repo:
	repo = console.input_alert("Repository", "Enter your GitHub Repository name", '', "Save")
	keychain.set_password('GitHub', 'repository', repo)

# Mangle the post ;)
post_text = editor.get_text()
Esempio n. 39
0
 def getname(self):
     return console.input_alert("Enter name")
Esempio n. 40
0
from xml.dom import minidom
import re
import csv
import prettytable
import StringIO
import console

u = '[SPLUNK USER HERE]'
p = '[SPLUNK USER PASSWORD HERE]'
url = '[SPLUNK MANAGEMENT URL HERE - e.g. https://splunkserver.com:8089]'

authservice = '/services/auth/login'
searchservice = '/services/search/jobs'

#Prompt for adhoc search
search = console.input_alert("enter search")


class SplunkSearch():
    def __init__(self):
        print('initialised')

    def encodeUserData(self, user, password):
        return urllib.urlencode({'username': user, 'password': password})

    def executesearch(self, searchquery):
        req = urllib2.Request(url + authservice)
        creds = self.encodeUserData(u, p)
        res = urllib2.urlopen(req, creds)
        sessionxml = res.read()
        sessionkey = minidom.parseString(sessionxml).getElementsByTagName(
Esempio n. 41
0
#!python2

# coding: utf-8

# https://forum.omz-software.com/topic/2973/file-manager-rename-and-copy-functions/2

import console
import editor
import os
import shutil

DOCUMENTS = os.path.expanduser("~/Documents")

old_name = editor.get_path()
new_name = os.path.join(
    DOCUMENTS,
    console.input_alert("Duplicate File", "Enter new name",
                        os.path.relpath(old_name, DOCUMENTS)))

if os.path.exists(new_name):
    console.hud_alert("Destination already exists", "error")
else:
    shutil.copy(old_name, new_name)

    ##editor.open_file(os.path.relpath(new_name, DOCUMENTS)) # For old Pythonistas
    editor.open_file(new_name)
Esempio n. 42
0
    isLink = console.alert('', '', 'Blockquote', 'No Blockquote')
    if isLink == 1:
        f.write('> ' + clipboard.get())
    f.close()


# Upload draft to Dropbox
def upload(slug, dropbox_draft_path):
    print(('\nUploading ' + slug + '.md'))
    f = open(slug + '.md')
    db = dropboxlogin.get_client()
    response = db.put_file(dropbox_draft_path + slug + '.md', f)
    remove(slug + '.md')


if __name__ == '__main__':
    # Path to drafts folder
    dropbox_draft_path = '/Blog/blog/drafts/'

    print((sys.argv[1]))
    url = sys.argv[1]
    title = sys.argv[2]
    title = console.input_alert('Edit Title', '', title)
    slug = console.input_alert('Edit Slug', '', convert_title(title))
    makefile(slug, url, title)
    upload(slug, dropbox_draft_path)

    # Open draft in Nebulous Notes
    nebulous = 'nebulous:/' + dropbox_draft_path + slug + '.md'
    webbrowser.open(nebulous)
Esempio n. 43
0
    if d['status'] == 'finished':
        console.hide_output()
        chosen = console.alert(
            'Download Finished',
            "Video is already in Pythonista.\nWaht else do you want to do with it?",
            'Quick Look', 'Open in', 'Save to Album')
        if chosen == 1:
            console.quicklook(d['filename'])
        elif chosen == 2:
            console.open_in(d['filename'])
        elif chosen == 3:
            save_video(d['filename'].encode('utf-8'))


if appex.is_running_extension() and re.search(
        'https*:\/\/[^\s]+',
        appex.get_attachments()[0]) is not None:
    url = appex.get_attachments()[0]
else:
    clip = re.search('https*:\/\/[^\s]+', clipboard.get())
    if clip is None:
        url = console.input_alert('URL Input')
    else:
        url = clipboard.get()

console.clear()

config = input('input config: ')
sys.argv = ['you-get', '%s' % config, '%s' % url]
you_get.main()
                                       Image.FLIP_LEFT_RIGHT),
            (Image.ROTATE_90, Image.FLIP_LEFT_RIGHT), (Image.ROTATE_270, None),
            (Image.ROTATE_270, Image.FLIP_LEFT_RIGHT), (Image.ROTATE_90,
                                                        None))[o - 1]

    if not (f is None):
        img = img.transpose(f)
    if not (r is None):
        img = img.transpose(r)

    width, height = img.size

    #Prompt for new width and height.
    width2 = adjust(
        width,
        console.input_alert("Width", "Enter new image width.", str(width)))

    height = int(height * (float(width2) / width))
    height2 = adjust(
        height,
        console.input_alert("Height", "Enter new image height.", str(height)))

    #Scale and save new image.
    img = img.resize((width2, height2), Image.ANTIALIAS)
    if photos.save_image(img):
        msg = "Saved."
    else:
        msg = "Save failed."

    console.alert(msg, button1="OK", hide_cancel_button=True)
Esempio n. 45
0
                          'Cast'
                      }, {
                          'type':
                          'switch',
                          'key':
                          'imdb_field',
                          'value':
                          moviediary_config['imdb_field'],
                          'title':
                          'IMDB URL'
                      }])])

        if moviediary_edit != None:
            if moviediary_edit['moviedb_api'] == '':
                moviedb_api = console.input_alert(
                    'Insert your TMDB API key', '',
                    '84cef43ccf02b1ba6093c9694ed671c9')
                if moviedb_api == None:
                    raise MissingConfigError(
                        'You need a valid MovieDB API key')
                else:
                    moviediary_edit['moviedb_api'] = moviedb_api

            if moviediary_edit['airtable_api'] == '':
                airtable_api = console.input_alert(
                    'Insert your Airtable API key')
                if airtable_api == None:
                    raise MissingConfigError(
                        'You need a valid Airtable API key')
                else:
                    moviediary_edit['airtable_api'] = airtable_api
Esempio n. 46
0
def main(args=None):
    ap = argparse.ArgumentParser()
    ap.add_argument('-c',
                    '--current-file',
                    action='store_true',
                    help='Use file currently opened in editor as input')
    ap.add_argument('-e',
                    '--edit-buffer',
                    action='store_true',
                    help='Use content of current editor buffer as input')
    ap.add_argument('infile', nargs='?', help='Input file name')

    args = ap.parse_args(args if args is not None else sys.argv[1:])

    if args.edit_buffer or args.current_file:
        pdf_bn = make_pdf_filename(editor.get_path())

    if args.current_file:
        with open(editor.get_path()) as f:
            md = f.read()
    elif args.edit_buffer:
        md = editor.get_text()
    elif args.infile:
        pfd_bn = make_pdf_filename(args.infile)
        with open(args.infile) as f:
            md = f.read()
    else:
        pdf_bn = 'markdown2pdf.pdf'

        try:
            choice = console.alert('Markdown to PDF', '', 'Show README',
                                   'Convert Clipboard', 'Convert URL')
        except KeyboardInterrupt:
            return

        if choice == 1:
            md = __doc__
        elif choice == 2:
            import clipboard
            md = clipboard.get()
        elif choice == 3:
            import re
            import clipboard
            try:
                cb = clipboard.get().strip()
                if not re.search('^(ht|f)tps?://', cb):
                    cb = ''
                url = console.input_alert('Enter URL',
                                          'Download Markdown from URL:', cb,
                                          'Download')
            except KeyboardInterrupt:
                return
            else:
                import urllib2
                import urlparse
                try:
                    r = urllib2.urlopen(url)
                except urllib2.URLError as exc:
                    print(exc)
                    console.hud_alert("Download error (see console)", 'error')
                    return
                else:
                    md = r.read()

                url = urlparse.urlparse(r.geturl())
                fn = make_pdf_filename(url.path)
                if fn:
                    pdf_bn = fn

    if not md:
        return

    tempdir = tempfile.mkdtemp()
    pdf_path = join(tempdir, pdf_bn)
    console.show_activity()
    status = markdown2pdf(md, pdf_path)
    console.hide_activity()

    try:
        choice = console.alert('Select Ouput', '', 'Save to file...',
                               'Open in...', 'View')
    except KeyboardInterrupt:
        return

    if choice == 1:
        try:
            filename = console.input_alert(
                "Filename",
                "Enter PDF output filename\n(will overwrite existing files!):",
                pdf_bn, 'Save')
            os.rename(pdf_path, filename)
        except KeyboardInterrupt:
            return
        except (IOError, OSError) as exc:
            console.alert("Error", "Error writing PDF file:\n\n%s" % exc)
            return 1
    elif choice == 2:
        console.open_in(pdf_path)
    elif choice == 3:
        console.quicklook(pdf_path)

    try:
        os.unlink(pdf_path)
        os.rmdir(tempdir)
    except:
        pass
Esempio n. 47
0
File: DRC.py Progetto: cclauss/DRC
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# DownloadRedditComments by GoDzM4TT3O
# I worked really hard on this, unicode errors and that stuff. The program would throw an error because of unicode characters. in my case I had \u2019 in my comments, now problem is fixed. THANK GOD.
# You can try it yourself - if you comment out 'content' and rename 'contentold' to 'content', and put my username (when you run the script), you will get an error with \u2019

import console, json, urllib.request, time, re, unicodedata

freq = console.input_alert(
    "DRC by GoDzM4TT3O",
    "Please enter a comment frequency. Choose one of these:\n\nday\nweek\nmonth\nyear"
)

if freq == 'day':
    freq = 'day'
elif freq == 'week':
    freq = 'week'
elif freq == 'month':
    freq = 'month'
elif freq == 'year':
    freq = 'year'
else:
    console.alert(
        "DRC by GoDzM4TT3O",
        "Choose a valid comment frequency.\nList of valid post frequencies:\n\nday\n\nweek\n\nmonth\n\nyear"
    )

limit = console.input_alert(
    "DRC by GoDzM4TT3O",
    "How many comments would you like to download? [Example: 50]\nMUST BE 10 or more."
)
Esempio n. 48
0
            url = console.input_alert('请输入m3u8资源地址:')
        else:
            url = clipboard.get()

    new_file_name = download_m3u8(url)
    if new_file_name != '':
        print('================================')
        print('下载完毕,存储为 this phone/ppcxy_download/m3u8目录\n文件名:')
        print(new_file_name + '.ts')
        print('请使用支持ts格式播放器播放')
        print('================================')


if __name__ == "__main__":
    if len(sys.argv) >= 2 and sys.argv[1] != '':
        m3u8_file = '%s%s' % (sys.argv[1], '.m3u8.tmp')
        logfile = '%s%s' % (sys.argv[1], 'm3u8.log')
        tem_ts_path = '%s%s' % (sys.argv[1], 'ts')
        print('手动合并,正在合并.........')
        join_file(tem_ts_path, sys.argv[1] + '.ts')
        print('合并完成,执行文件清理.........')
        rm_file(m3u8_file)
        rm_file(tem_ts_path)
        rm_file(logfile)
        new_file_name = console.input_alert('处理完毕,是否修改文件名?(不修改直接确定):', '',
                                            sys.argv[1])
        if new_file_name != '':
            os.rename(sys.argv[1] + '.ts', new_file_name + '.ts')
    else:
        main()
Esempio n. 49
0
 def change_description(self):
     self.description = console.input_alert(
         title='Enter Element Description',
         message='Enter a description for the element')
     table_view.reload()
Esempio n. 50
0
numArgs = len(sys.argv)

if numArgs == 2:
	redirect = sys.argv[1]
elif numArgs < 2:
	redirect = clipboard.get()
	
# Provided by Peter Hansen on StackOverflow:
# http://stackoverflow.com/questions/1986059/grubers-url-regular-expression-in-python/1986151#1986151
pat = r'\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^%s\s]|/)))'
pat = pat % re.escape(string.punctuation)


match = re.findall(pat, redirect)

if match:
	for x in match:
		console.show_activity()
		# Get the first match without redirects
		cleaned = urllib.request.urlopen(x[0]).geturl()
		# Get direct image link
		cleaned = cleaned.replace('www.dropbox.com', 'dl.dropboxusercontent.com')
		title = console.input_alert('Image text', 'Type the image alt text below.')
		final = '![' + title + '](' + cleaned + ')'
		clipboard.set(final)
		print('Done.')
elif not match:
	console.alert('No match found')


Esempio n. 51
0
import Image, ImageOps, ImageFilter
import photos
import console
import clipboard
import datetime

img = photos.pick_image()

today = datetime.datetime.now()
# image = clipboard.get_image()
fileName = console.input_alert("Image Title", "Enter Image File Name")
fileName = fileName + '_' + today.strftime("%Y-%m-%d-%H%M%S") + '.png'


def customSize(img):
    w, h = img.size
    print 'w: ' + str(w)
    print 'h: ' + str(h)
    if w > 600:
        wsize = 600 / float(w)
        print 'wsize: ' + str(wsize)
        hsize = int(float(h) * float(wsize))
        print 'hsize: ' + str(hsize)

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


image = customSize(img)

# final = choose.resize((800,600),Image.ANTIALIAS)
Esempio n. 52
0
if not clipboard.get_image(idx=0):
    print 'I don\'t think there are any images on the clipboard.'
    sys.exit()

resizeAmountQ = console.alert(
    'What percent of original size?', '',
    '{0}% (default for {1})'.format(reduction_amounts[q1], q1),
    '{0}% (default for {1})'.format(reduction_amounts[q2], q2), 'Custom')
if resizeAmountQ == 1:
    resizeAmount = float(reduction_amounts[q1]) / 100
elif resizeAmountQ == 2:
    resizeAmount = float(reduction_amounts[q2]) / 100
elif resizeAmountQ == 3:
    resizeAmount = float(
        console.input_alert('What percent of original size?', 'Number only',
                            '40')) / 100
else:
    print 'Whups!'
    sys.exit()

x = 0
while True:
    img = clipboard.get_image(idx=x)

    if img:
        width, height = img.size

        smaller = img.resize(
            (int(width * resizeAmount), int(height * resizeAmount)),
            Image.ANTIALIAS)
        photos.save_image(smaller)
Esempio n. 53
0
 def tableview_did_select(self, tableview, section, row):
     param = self.params[row]
     name = param.displayName
     value = param.value
     noVariable = True
     if param.isVariableAllowed:
         choice = console.alert(
             title='Variable Available',
             message='Would you like to choose a variable?',
             button1='Choose Variable',
             button2='Ask when run',
             button3='Don\'t use a variable')
         if choice == 1:
             noVariable = False
             param.useVariable = True
             param.variableName = console.input_alert(
                 title='Option', message='Please enter the variable name')
             param.value = None
             param.askAtRuntime = False
         elif choice == 2:
             noVariable = False
             param.useVariable = True
             param.value = None
             param.askAtRuntime = True
             param.variableName = ''
         else:
             noVariable = True
             param.useVariable = False
             param.askAtRuntime = False
             param.variableName = ''
     if name == None or name == '':
         name = param.name
     if value == None:
         value = ''
     if noVariable and param.type == 'string':
         param.value = console.input_alert(name, '', value)
     elif noVariable and param.type == 'int':
         param.value = int(console.input_alert(name, '', str(value)))
     elif noVariable and param.type == 'variable':
         pass
     elif noVariable and param.type == 'list':
         ret = dialogs.list_dialog(title=name,
                                   items=param.allowedValues,
                                   multiple=param.multipleAllowed)
         yo = ''
         if not ret == None:
             if isinstance(ret, list):
                 for item in ret:
                     yo += item + ','
             else:
                 yo = ret
             yo = yo.rstrip(',')
         param.value = yo
     elif noVariable and param.type == 'dictionary':
         self.dictionaryParam = param
         self.dictView = ElementParameterDictionaryInputView.get_view(
             dictionary=param.value,
             title=name,
             cb=self.dictionaryReturn,
             thememanager=self.thememanager)
         self.tv = tableview
         self.dictView.title_bar_color = self.thememanager.main_bar_colour
         self.dictView.tint_color = self.thememanager.main_tint_colour
         self.dictView.present(orientations=['portrait'])
     elif noVariable and param.type == 'Boolean':
         pass
     tableview.reload()
Esempio n. 54
0
"""
Created on Sat Jul 12 09:33:29 2014

@author: henryiii

Added improvents by JonB (swipes), techteej (design), LawAbidingCactus (size)
"""
from __future__ import print_function

import console, random
import numpy as np
from functools import partial
import time
import ui

size = int(console.input_alert('2048', 'What size?', '4'))
#GAME_FONT = 'ClearSans-Bold' # need to install this font, this is what the actual 2048 uses
GAME_FONT = 'AppleSDGothicNeo-Bold'
COLORS = (
    (0.93333333333, 0.89411764705, 0.85490196078),
    (0.93333333333, 0.89411764705, 0.85490196078),
    (0.9294117647, 0.87843137254, 0.78431372549),
    (0.94901960784, 0.69411764705, 0.47450980392),
    (0.96078431372, 0.58431372549, 0.38823529411),
    (0.96470588235, 0.4862745098, 0.3725490196),
    (0.96470588235, 0.36862745098, 0.23137254902),
    (0.9294117647, 0.81176470588, 0.44705882352),
    (0.9294117647, 0.8, 0.38039215686),
    (0.9294117647, 0.78431372549, 0.31372549019),
    (0.9294117647, 0.7725490196, 0.24705882352),
    (0.9294117647, 0.76078431372, 0.18039215686),
Esempio n. 55
0
        if GET_TEXT is None:
            console.hud_alert(name + " is a builtin module.", "error")
            return

        document_string = '''# Please Note: This is a module CLONE! It *may* (hopefully not) have errors caused by the transfer script!\n# This module was cloned using {} version {} on mode {}\n# Cloned module: {}{}\n\n'''.format(
            __name__, __version__, mode, name, locater.cur_suffix)
        copyname = name + "_copy.py"

        moduletext = document_string + GET_TEXT

        with open(copyname, 'w') as fw:
            fw.write(moduletext)
        console.hud_alert("Cloned!")

    console.clear()
    name = console.input_alert('Name:')
    attempts = 0
    path = sys.path[0] + name + suffixs[0]
    start = sys.path[0]
    main()

if mode == 1:
    # use inspect module to get source file

    import inspect
    import console
    name = console.input_alert("Module to clone")
    try:
        exec "import " + name
    except ImportError:
        console.hud_alert("cant find " + name, "error")
Esempio n. 56
0
# coding: utf-8
# 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\" />"

console.clear()

print(final)

clipboard.set(final)

print("\n \n HTML set to clipboard")


Esempio n. 57
0
#Summary: Takes copied text and creates new task in OmniFocus
#By: Jason Verly
#Rev: 2013-02-04
#Rev Note: Added Page Title & URL to clipped txt

import webbrowser
import clipboard
import urllib
import console
import sys

title = sys.argv[1]
url = sys.argv[2]

task = console.input_alert('Task', 'Enter task description')
task = urllib.quote(task)

note = clipboard.get()

full_note = ''.join([title, '\n\n', url, '\n\n', note])
full_note = urllib.quote(full_note.encode('utf-8'))

webbrowser.open('omnifocus:///add?name=' + task + '&note=' + full_note)
Esempio n. 58
0
# https://gist.github.com/omz/4177224

# Original script by Federico Viticci:
# http://www.macstories.net/reviews/fantastical-for-iphone-review/
# Modified to work better with international characters

import webbrowser
import clipboard
import urllib
import console

when = clipboard.get()

fant = 'fantastical://parse?sentence='

newtask = console.input_alert('What is this?', 'Type your event below')

loc = console.alert('Location', 'Does the event have a location?', 'Yes', 'No')

if loc == 1:
    place = console.input_alert('Where', 'Type your location below')

    event = newtask.decode('utf-8') + ' ' + when + ' at ' + place.decode(
        'utf-8')

    encoded = urllib.quote(event.encode('utf-8'), safe='')

elif loc == 2:
    event = newtask.decode('utf-8') + ' ' + when
    print type(event)
    encoded = urllib.quote(event.encode('utf-8'), safe='')
Esempio n. 59
0
 def show_input(self):
     self.output = console.input_alert('Please enter text')
Esempio n. 60
0
def entername():
    mytext = console.input_alert('Please enter text:')
    textlabel = v['textlabel']
    textlabel.text = mytext