コード例 #1
0
ファイル: Launcher.py プロジェクト: DocVaughan/Pythonista
def main():
	if not appex.is_widget():
		print('This script must be run in the Pythonista Today widget (in Notification Center). You can configure the widget script in the settings.')
		return
	console.clear()
	v = appex.get_widget_view()
	# If the shortcuts change, change the view name as well,
	# so it is reloaded.
	view_name = 'Launcher_' + str(shortcuts)
	# Check if the launcher view already exists, if not,
	# create it, and set it as the widget's view.
	if not v or v.name != view_name:
		h = math.ceil(len(shortcuts) / 3) * 44
		v = ui.View(frame=(0, 0, 300, h))
		# Create a button for each shortcut
		for i, s in enumerate(shortcuts):
			btn = ui.Button(title=s['title'])
			btn.image = ui.Image.named(s['icon'])
			btn.frame = ((i % 3) * 100, (i // 3) * 44, 100, 44)
			btn.flex = 'LRWH'
			btn.tint_color = 'white'
			# Just store the shortcut URL in the button's name attribute.
			# This makes it easy to retrieve it in the button_tapped action.
			btn.name = s['url']
			btn.action = button_tapped
			v.add_subview(btn)
		v.name = view_name
		appex.set_widget_view(v)
コード例 #2
0
def split():
	console.clear()
	printEx('Now spliting ...')
	if not im:
		printEx('Please select one picture.')
		return
	im1 = resize_auto_scale(im,1024,1024)
	(w,h) = im1.size
	ww = math.floor(w / col)
	hh = math.floor(h / (num /3))
	printEx(im1.size,info_type.info)
	imgs = []
	boxs = []
	for i in range(num):
		_x = (i % col)*ww
		_y = math.floor((i)/col) * hh
		
		printEx('[%d] x:%d,y:%d,w:%d,h:%d'%(i,_x,_y,ww,hh),info_type.info)
		boxs.append((_x,_y,ww+_x,hh+_y))
		
		_img = im1.crop([_x,_y,ww+_x,hh+_y])
		imgs.append(_img)
		printEx(_img.size,info_type.debug)
		printEx(_img.mode,info_type.debug)

	printEx(boxs, info_type.debug)
	image_files = []
	for _idx,ix in enumerate(imgs):
		_f_name = '%s/split_%d.jpg'%(image_path,_idx)
		ix.save(_f_name)
		image_files.append(_f_name)
	printEx('\nsucess!!save to %s'%image_path)

	save2Album(image_files)
コード例 #3
0
def main():
    console.clear()
    
    class BrythonRunner(wkwebview.WKWebView):
        
        @on_main_thread
        def load_html(self, html):
            # Need to set a base directory to get
            # real js errors
            current_working_directory = os.path.dirname(editor.get_path())
            root_dir = NSURL.fileURLWithPath_(current_working_directory)
            self.webview.loadHTMLString_baseURL_(html, root_dir)
        
        def _message(self, message):
            level, content = message['level'], message['content']
            
            if level not in ['code', 'raw']:
                if content == 'using indexedDB for stdlib modules cache':
                    #print('Brython started')
                    return
                
                if level.upper() == 'LOG':
                    print(content,
                    end=('' if content.endswith('\n') else '\n'))
                    return
            
            super()._message(message)    
              
    python_code = editor.get_text()
    
    wv = BrythonRunner()
    
    html = html_start + python_code + html_end
    
    wv.load_html(html)
コード例 #4
0
def config_consola(localizacao):
    '''
    Sets console font size and color for Pythonista on iOS
    '''
    console.clear()
    console.set_font("Menlo-Bold", HEADER_FONTSIZE)

    if DARK_MODE:
        console.set_color(0.5, 0.8, 1)
    else:
        console.set_color(0.2, 0.5, 1)

    line_length = 32
    if len(localizacao + __app_name__ + ' ') > line_length:
        str_title = "{}\n({})".format(__app_name__, localizacao)
    else:
        str_title = "{} ({})".format(__app_name__, localizacao)

    print(str_title)
    console.set_font("Menlo-Regular", 6.7)

    if DARK_MODE:
        console.set_color(0.7, 0.7, 0.7)
    else:
        console.set_color(0.5, 0.5, 0.5)
    print(f'{__copyright__}, {__license__}\n\n')
コード例 #5
0
def main():
    console.clear()
    i = console.alert('Info', 'This script detects faces in a photo.',
                      'Take Photo', 'Pick from Library')
    if i == 1:
        filename = take_photo()
    else:
        filename = pick_photo()
    if not filename:
        return
    ci_img = load_ci_image(filename)
    out_file = write_output(ci_img)
    console.show_image(out_file)
    faces = find_faces(ci_img)
    if faces.count() == 0:
        print(
            'Error: Could not find a face in the photo. Please try again with a different image.'
        )
        return
    j = 0
    for face in faces:
        b = face.bounds()
        w = b.size.width
        h = b.size.height
        rt = CGPoint(b.origin.x + w, b.origin.y + h)
        rb = CGPoint(b.origin.x + w, b.origin.y)
        lt = CGPoint(b.origin.x, b.origin.y + h)
        lb = CGPoint(b.origin.x, b.origin.y)
        corners = (rt, rb, lt, lb)
        out_img = apply_perspective(corners, ci_img)
        j = j + 1
        out_file = write_output(out_img, filename='.output' + str(j) + '.jpg')
        console.show_image(out_file)
    print('Tap and hold the image to save it to your camera roll.')
コード例 #6
0
def main():
    console.clear()
    w, h = ui.get_screen_size()
    disp = 'full_screen'
    back = MyView(w, h)
    back.background_color = 'white'
    back.present(disp, hide_title_bar=True)
コード例 #7
0
def main():
	console.clear()
	dest_path_short = '~/Documents/inbox'
	dest_path = os.path.expanduser(dest_path_short)
	if not os.path.isdir(dest_path):
		print('Create ' + dest_path_short)
		os.mkdir(dest_path)
	if not appex.is_running_extension():
		print('Using clipboard content...')
		text = clipboard.get()
		assert text, 'No text on the clipboard!'
		resp = console.alert('Alert!', 'Choose File Extension', '.py', '.pyui', hide_cancel_button=False)
		if resp==1:
			ext = '.py'
		elif resp==2:
			ext = '.pyui'
		filename=os.path.join(dest_path,'clipboard')
		filename=getuniquename(filename,ext)
		while os.path.isfile(filename):
			filename = '{} {}{}'.format(root, filenum, extension)
			filenum += 1
		with open(filename,'w') as f:
			f.write(text)
		print('Done!')
	else:
		file = appex.get_file_path()
		print('Input path: %s' % file)
		filename=os.path.join(dest_path, os.path.basename(file))
		filename=getuniquename(filename,'')
		shutil.copy(file,filename)
	print('Saved in %s' % dest_path_short)
	if not os.path.exists(filename):
		print(' > Error file %s not found !' % os.path.basename(filename))
	else:
		print(' > as %s' % os.path.basename(filename))
コード例 #8
0
ファイル: listApp.py プロジェクト: c0ns0le/Pythonista
def main():
    console.clear()
    fileName = 'listApp.txt'
    theList = readListFromFile(fileName)
    theList = mainLoop(theList)
    writeListToFile(fileName, theList)
    print('Thank you for using listApp.')
コード例 #9
0
def main():
	now = datetime.datetime.now()
	ymd = now.strftime('%Y-%m-%d')
	doc_path = os.path.expanduser('~/Documents')
	os.chdir(doc_path)
	backup_path = os.path.join(doc_path, 'Backup-'+ymd+'.zip')
	if os.path.exists(backup_path):
		os.remove(backup_path)
	print('Creating backup archive...')
	
	shutil.make_archive(os.path.join(tempfile.gettempdir(), 'Backup-'+ymd), 'zip')
	shutil.move(os.path.join(tempfile.gettempdir(), 'Backup-'+ymd+'.zip'), backup_path)
	print('Backup archive created, starting HTTP server...\n')
	local_url = 'http://localhost:{}/Backup-{}.zip'.format(PORT, ymd)
	wifi_url = 'http://%s:%i/Backup-%s.zip' % (get_ip_address(), PORT, ymd)
	server = HTTPServer(('', PORT), SimpleHTTPRequestHandler)
	console.clear()
	print('You can tap the following link to open the backup Zip archive in Safari (from where you can transfer it to other apps on this device):')
	console.write_link(local_url + '\n', 'safari-' + local_url)
	print('\nIf you want to transfer the backup to another device in your local WiFi network, enter the following URL in a web browser on the other device:')
	print(wifi_url)
	print('\n====\nTap the stop button in the editor or console when you\'re done.')
	try:
		server.serve_forever()
	except KeyboardInterrupt:
		server.shutdown()
		server.socket.close()
		print('Server stopped')
コード例 #10
0
def main():
  if consoleExists:
    console.clear()
  ignored = '''
  attrs = (
    (0, 0, 0, 7),
    (0, 0, 3, 2),
    (1, 0, 0, 4),
    (2, 0, 0, 1),
    (2, 0, 0, 2),
    (1, 1, 1, 1)
  )
  '''

  attrs = (
    (1, 0, 0, 0),
    (0, 1, 0, 0),
    (0, 1, 0, 0),
    (0, 0, 1, 0),
    (0, 0, 1, 0),
    (0, 0, 1, 0)
  )
  
  dmg = 0
  
  for lp in attrs:
    dmg += sum([ d[0] * d[1] for d in zip(lp, dieTypeDmg)])
    
  print(str(dmg) + ' damage')
コード例 #11
0
def adjust_for_platform() -> Tuple[int, Union[TPoolExType, PPoolExType], int]:
    if platform.system() == 'Darwin':
        if platform.machine().startswith('iPad'):
            device = "iPad"
        elif platform.machine().startswith('iP'):
            device = "iPhone"
        else:
            device = "mac"
    else:
        device = "other"

    if device in ("iPad", "iPhone"):
        # Adapt for smaller screen sizes in iPhone and iPod touch
        import ui
        import console
        console.clear()
        if device == 'iPad':
            font_size = IPAD_FONT_SIZE
        else:
            font_size = IPHONE_FONT_SIZE
        console.set_font(IOS_FONT, font_size)
        screen_width = ui.get_screen_size().width
        char_width = ui.measure_string('.', font=(IOS_FONT, font_size)).width
        line_width = int(screen_width / char_width - 1.5) - 1
        pool_ex = concurrent.futures.ThreadPoolExecutor
        workers = IOS_WORKERS
    else:
        line_width = shutil.get_terminal_size((80, 24)).columns
        pool_ex = concurrent.futures.ProcessPoolExecutor
        from multiprocessing import cpu_count
        workers = cpu_count() + 1

    return line_width, pool_ex, workers
コード例 #12
0
def listData(d):
  #print d
  #sys.exit()

  the_films = []
  the_ids = []

  # Loop through list of titles and append all but episodes to film array
  for title in d['Search']:
    if title['Type'] != 'episode':
      the_films.append(', '.join([title['Title'], title['Year'], title['Type']]))
      # Add film's imdbID to the ids array
      the_ids.append(title['imdbID'])

  while True:
    # Print out a new list of film choices
    for index, item in enumerate(the_films):
      print index, item
    try:
      '''
      Number of film selected will
      match the  index number of that
      film's imdbID in the ids array.
      '''
      film_idx = int(raw_input("\nEnter the number of your desired film or TV series: ").strip())
      film_id = the_ids[film_idx]
      break
    except (IndexError, ValueError):
      choice = raw_input('\nInvalid entry...Continue? (y/n): ').strip().lower()
      console.clear()
      if not choice.startswith('y'):
        sys.exit('Process cancelled...Goodbye')

  # Return the film's imdbID to the caller
  return film_id
コード例 #13
0
ファイル: SAT_Calc.py プロジェクト: kmaiya/mySATCalc
def menu2(user):
	print 'What would you like to do?\n'
	print 'Enter New Scores(n)\nView Result Graph(r)\nQuick Input(qi)\nLogout(lo)\nQuit(q)'
	inp = raw_input().lower()
	if inp == 'q':
		console.clear()
		print 'Thank you for using mySATCalc'
		sys.exit()
	elif inp == 'n':
		newTest(user)
	elif inp == 'r':
		grapher(user)
		plt.show()
		plt.close()
		menu2(user)
	#elif inp == 'c':
		#str = raw_input('Enter usernames of the people you want to compare to yourself seperated by spaces\n')
		#arr = str.split()
		#comparePlot(arr,user)
		#plt.show()
		#plt.close()
		#menu2(user)
	elif inp == 'lo':
		menu1()
	elif inp == 'qi':
		score = raw_input('Enter score out of 2400')
		writeToFile(user,score)	
	else:
		menu2(user)
コード例 #14
0
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! ----")
コード例 #15
0
def main():
    zip_dir = ZIP_DIR
    excludelist = EXCLUDES

    excludelist.append(zip_dir)
    source_dir = os.path.join(os.path.expanduser("~"), "Documents")
    zip_dir_full = os.path.join(source_dir, zip_dir)
    fname = datetime.datetime.now().strftime(
        "Scripts Backup - %m%d%Y - %I:%M %p.zip")
    zip_file = os.path.join(zip_dir_full, fname)

    try:
        os.stat(zip_dir_full)
    except:
        os.mkdir(zip_dir_full)
    if not os.path.isdir(zip_dir_full):
        console.hud_alert(
            "Could not create zip dest dir {zdf}".format(zdf=zip_dir_full),
            'error', 1.5)
        sys.exit()

    make_zipfile(zip_file, source_dir, excludelist)
    bytes = "Backup Successfully Created - {fs} bytes written".format(
        fs=os.path.getsize(zip_file))
    console.hud_alert(bytes, 'success', 1.5)
    dropbox('rso5vcsund16lw9', 'wqivu6pzm3ef93s', 'app_folder', zip_file)
    console.clear()
    console.hud_alert('Uploaded to Dropbox!', 'success', 1.5)
コード例 #16
0
ファイル: iTC Downloader.py プロジェクト: someburner/GistsHub
def main():
    console.clear()
    if RESET_LOGIN:
        keychain.delete_password('iTunesConnect', 'Default')
    user, password, vendor_id = get_login()
    # Create the data folder:
    data_dir = 'ITCData'
    try:
        os.mkdir(data_dir)
    except OSError:
        pass
    # Load exchange rates (cached for 12 hours):
    rates = load_exchange_rates(os.path.join(data_dir, 'ExchangeRates.json'))
    # Load sales reports for the last 30 days:
    print 'Loading sales reports...\n'
    today = datetime.datetime.now()
    for i in xrange(30, 0, -1):
        d = today - datetime.timedelta(i)
        date_str = '%04i%02i%02i' % (d.year, d.month, d.day)
        display_date_str = '%04i-%02i-%02i' % (d.year, d.month, d.day)
        try:
            report = load_report(user, password, vendor_id, date_str, data_dir)
            print_report_summary(display_date_str, report, rates, CURRENCY)
        except ITCDownloadError, e:
            print 'Download failed for', display_date_str, '---', e
コード例 #17
0
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! ----")
コード例 #18
0
def main(argv):
    console.clear()
    print('Testing utility functions')
    # get_timestamp(in_datetime = None)
    print(get_timestamp())
    print(get_timestamp(datetime.datetime.strptime('02/13/1970', '%m/%d/%Y')))
    # get_user_choice(in_title, in_prompt, in_choices, in_allow_cancel = True)
    print(get_user_choice('get_user_choice()', 'prompt -- can cancel', ('1', '2', '3')))
    print(get_user_choice('get_user_choice()', 'prompt -- can not cancel', ('1', '2', '3'), False))
    # get_user_input(in_prompt, in_allow_cancel = True)
    print(get_user_input('get_user_input() -- can cancel'))
    print(get_user_input('get_user_input() -- can not cancel', False))
    # get_user_integer(in_prompt, in_min = 0, in_max = 100000, in_allow_cancel = True)
    print(get_user_integer('get_user_integer() -- can cancel', 1, 10))
    print(get_user_integer('get_user_integer() -- can not cancel', 1, 10, False))
    # get_user_float(in_prompt, in_min = 0.0, in_max = 100000.0, in_allow_cancel = True)
    print(get_user_float('get_user_float() -- can cancel', 1.0, 10.0))
    print(get_user_float('get_user_float() -- can not cancel', 1.0, 10.0, False))
    # get_user_special_float(in_prompt, in_min = 0.25, in_max = 48.0, in_allow_cancel = True)
    print(get_user_special_float('get_user_special_float() -- can cancel', 1.0, 10.0))
    print(get_user_special_float('get_user_special_float() -- can not cancel', 1.0, 10.0, False))
    # get_user_photo(in_allow_none = True) and save_user_photo(photo, task_name)
    print('get_user_photo() -- allow None')
    save_user_photo(get_user_photo(), 'My task name')
    print('get_user_photo() -- do not allow None')
    save_user_photo(get_user_photo(False), None)
コード例 #19
0
def main():

	console.clear()
	#p = photos.pick_image(show_albums=True, include_metadata=True, original=True, raw_data=False, multi=True)
	# Build dictionary filename: index
	fn_index = {}
	for ip in range(photos.get_count()):
		m = photos.get_metadata(ip)
		#print m
		fn = m.get('filename')
		fn_index[fn] = (ip,'')	

	# - type = 1: album
	# - subtype = 2: regular album
	result = PHAssetCollection.fetchAssetCollectionsWithType_subtype_options_(1,2, None)
	#print result
	for i in range(result.count()):
		coll = result.objectAtIndex_(i)
		album = str(coll.localizedTitle())
		assets = PHAsset.fetchAssetsInAssetCollection_options_(coll, None)
		for j in range(assets.count()):
			a = assets.objectAtIndex_(j)		
			fn = str(a.valueForKey_('filename'))
			tuple = fn_index[fn]
			ip = tuple[0]
			fn_index[fn] = (ip,album)
			
	# print filename -> album,index
	print fn_index
コード例 #20
0
def clearconsole():
	if has_console:
		console.clear()
	elif platform.system() == 'Windows':
		os.system('cls')
	else:
		os.system('clear')
コード例 #21
0
ファイル: Image2ASCII.py プロジェクト: cclauss/Image2ASCII
def PythonistaTest():
    '''A test of the module for iOS devices running Pythonista'''
    import console, photos, clipboard
    #Ask the user to either take a photo or choose an existing one
    capture = console.alert("Image2ASCII",
                            button1="Take Photo",
                            button2="Pick Photo")
    if capture == 1:
        im = photos.capture_image()
    elif capture == 2:
        im = photos.pick_image(original=False)
    photos.save_image(im)
    console.show_activity()
    out = image2ASCII(im, 200)
    outim = RenderASCII(out, bgcolor='#ededed')
    stitchImages(im, outim).show()
    console.hide_activity()
    outim.save('image.jpg')
    console.quicklook('image.jpg')
    mode = console.alert("Image2ASCII", "You can either:", "Share Text",
                         "Share Image")
    if mode == 1:
        file = open('output.txt', 'w')
        file.write(out)
        file.close()
        console.open_in('output.txt')
    elif mode == 2:
        console.open_in('image.jpg')
    time.sleep(5)
    console.clear()
コード例 #22
0
def main():

	#----- Main process -----
	console.clear()
	
	if not appex.is_running_extension():
		#img = photos.pick_image()
		console.hud_alert('Must run in appex mod','error')
		return
	else:
		img = appex.get_image(image_type='pil')
		
	if img == None:
		console.alert('No image passed','','Ok',hide_cancel_button=True)
		return
		
	lat,lon, lat_lon_txt = get_gps(img)
	
	if not lat or not lon:
		console.alert('No GPS tags in image','','Ok',hide_cancel_button=True)
		return
		
	# Hide script
	back = MapView(frame=(0, 0, 540, 620))
	back.background_color='white'
	back.name = 'GPS = '+lat_lon_txt
	back.present('sheet', hide_title_bar=False)
	
	back.set_region(lat, lon, 0.05, 0.05, animated=True)
	back.add_pin(lat, lon,str((lat, lon)))
コード例 #23
0
def game_exit():
    console.clear()
    map1.draw()
    player1.draw()

    console.move_cursor(0, 24)
    pass
コード例 #24
0
def progress(pawns):
    new_fences = build()
    player_turn = 1
    state = State.RUNNING
    console.clear()
    console.prompt(
        "\n *** Welcome to PyQuoridor ***\n  Press Enter to start ...")
    new_pawns = deepcopy(pawns)
    while state == State.RUNNING:
        display(new_pawns, new_fences)
        action = console.prompt_action(player_turn)
        if action == Action.EXIT:
            state = State.QUIT
        else:
            try:
                new_pawns = deepcopy(new_pawns)
                new_pawn = act(action, new_pawns[player_turn - 1], new_fences)
                new_pawns[player_turn - 1] = new_pawn
                if is_a_victory(new_pawn):
                    state = State.VICTORY
                else:
                    player_turn = get_next_player(player_turn, new_pawns)
            except QuoridorException:
                pass
    if state == State.VICTORY:
        display(new_pawns, new_fences)
        console.display("\n *** Player # " + str(player_turn) + " won ***\n")
コード例 #25
0
def main(args):
  console.clear()
  clipboard.set('')
  '''
  Tap-and-hold on Pythonista run button to
  enter movie name as commandline
  arguments
  '''
  myTitle = ' '.join(args) or raw_input('Please enter a movie or TV series title: ').strip()
  if not myTitle:
    sys.exit('No title provided.')

  print "\nConnecting to server...wait"

  s = myTitle.replace(' ', '+')
  '''
  Use ?t to search for one item...this
  first pass will give you the most
  popular result for query, but not always
  the one you desire when there are
  multiple titles with the same name
  '''
  # Call subroutines
  d = queryData(url_fmt.format('t', s));
  print('='*20)
  print(mine_console_data(d))

  while True:
    # Give user a choice to refine search
    choice = raw_input('Refine your search? (y/n/c): ').strip().lower()
    # Accept 'Yes', etc.
    if choice.startswith('y'):
      print('='*20)
      # Use ?s for a query that yields multiple titles
      url = url_fmt.format('s', s)
      d = queryData(url)
      '''
      Call function to list all the titles
      in the query and return IMDB id
      for title chosen from list
      '''
      id = listData(d)
      print "\nRetrieving data from new query..."
      # Use ?i for an exact query on unique imdbID
      d = queryData(url_fmt.format('i', id));
      print('='*20)
      print(mine_console_data(d))
    elif choice.startswith('n'):
      # Clear clipboard, then add formatted text
      clipboard.set('')
      clipboard.set(mine_md_data(d))

      print '''
Results of your search were copied
to the clipboard in MD for use with
the MD text editor or journaling app
of your choice.''' + '\n\n'
      break
    else:
      sys.exit('Search Cancelled')
コード例 #26
0
ファイル: snippet.py プロジェクト: someburner/GistsHub
def main():
    console.clear()
    fileName = 'listApp.txt'
    theList = readListFromFile(fileName)
    theList = mainLoop(theList)
    writeListToFile(fileName, theList)
    print('Thank you for using listApp.')
コード例 #27
0
 def take_a_selfie(self, filename='.temp.jpg'):
     self.name = raw_input()
     self.selfie = raw_input()
     if 'selfie' in self.selfie:
         img = photos.capture_image()
         if img:
             img.save(filename)
             console.show_image(filename)
             speech.say(self.name + ', you look stunning!')
             print self.name + ', you look stunning!'
             speech.say(
                 'Would you like to save your master piece in a custom album?'
             )
             print 'Would you like to save your master piece in a custom album?'
             self.to_save_or_not_to_save = raw_input()
             if 'ye' in self.to_save_or_not_to_save:
                 photos.create_album(self.name + 's Album')
                 speech.say(
                     'Okay. I have created your own custom album to save your legendary pic.'
                 )
                 print 'Okay. I have created your own custom album to save your legendary pic.'
                 speech.say(
                     'Hold the image to save your elegant pic in your custom album'
                 )
                 print 'Hold the image to save your elegant pic in your custom album'
                 self.idle()
             else:
                 speech.say(
                     'Affirmative... Your photo will be deleted after this session.'
                 )
                 print 'Affirmative... Your photo will be deleted after this session.'
                 self.idle()
     console.clear()
コード例 #28
0
def main():
	#print sys.argv[:]
	
	filename = sys.argv[1]
	
	resp = console.alert(
		'Choose File Extension',
		'',
		'Detect Extension'+' (.'+sys.argv[2]+')',
		'.py',
		'Custom',
		hide_cancel_button=False
	)
	if resp==1:
		ext = '.'+sys.argv[2]
	elif resp==2:
		ext = '.py'
	elif resp==3:
		ext = console.input_alert('File extension', 'Type a file extension.', '.')
	
	if len(sys.argv) > 3:
		text = sys.argv[3]
	elif clipboard.get():
		text = clipboard.get()
		#console.alert('Used clipboard')
	assert text, 'No text captured!'
	
	console.clear()
	print('Wait a Moment Please!')
	console.clear()
	filename = save(filename, text, ext)
	print('Done!\nFile Saved as:\n' + filename)
コード例 #29
0
def main():

    console.clear()
    #p = photos.pick_image(show_albums=True, include_metadata=True, original=True, raw_data=False, multi=True)
    # Build dictionary filename: index
    fn_index = {}
    for ip in range(photos.get_count()):
        m = photos.get_metadata(ip)
        #print m
        fn = m.get('filename')
        fn_index[fn] = (ip, '')

    # - type = 1: album
    # - subtype = 2: regular album
    result = PHAssetCollection.fetchAssetCollectionsWithType_subtype_options_(
        1, 2, None)
    #print result
    for i in range(result.count()):
        coll = result.objectAtIndex_(i)
        album = str(coll.localizedTitle())
        assets = PHAsset.fetchAssetsInAssetCollection_options_(coll, None)
        for j in range(assets.count()):
            a = assets.objectAtIndex_(j)
            fn = str(a.valueForKey_('filename'))
            tuple = fn_index[fn]
            ip = tuple[0]
            fn_index[fn] = (ip, album)

    # print filename -> album,index
    print(fn_index)
コード例 #30
0
ファイル: interpreter.py プロジェクト: gilsim12/pcbasic
 def __init__(self, greet, load):
     """ Initialise the interpreter session. """
     # true if a prompt is needed on next cycle
     self.prompt = True
     # input mode is AUTO (used by AUTO)
     state.basic_state.auto_mode = False
     # interpreter is executing a command
     state.basic_state.parse_mode = False
     # interpreter is waiting for INPUT or LINE INPUT
     state.basic_state.input_mode = False
     # previous interpreter mode
     self.last_mode = False, False
     # syntax error prompt and EDIT
     state.basic_state.edit_prompt = False
     # initialise the display
     display.init()
     # initialise the console
     console.init_mode()
     # set up event handlers
     state.basic_state.events = events.Events()
     # load initial program
     if load:
         # on load, accept capitalised versions and default extension
         with disk.open_native_or_dos_filename(load) as progfile:
             program.load(progfile)
     # set up interpreter and memory model state
     reset.clear()
     # greeting and keys
     if greet:
         console.clear()
         console.write_line(greeting.format(version=plat.version, free=var.fre()))
         console.show_keys(True)
コード例 #31
0
ファイル: Image2ASCII.py プロジェクト: cclauss/Image2ASCII
def PythonistaTest():
	'''A test of the module for iOS devices running Pythonista'''
	import console,photos,clipboard
	#Ask the user to either take a photo or choose an existing one
	capture = console.alert("Image2ASCII", button1="Take Photo", button2="Pick Photo")
	if capture == 1:
		im = photos.capture_image()
	elif capture == 2:
		im = photos.pick_image(original=False)
	photos.save_image(im)
	console.show_activity()
	out = image2ASCII(im, 200)
	outim = RenderASCII(out, bgcolor = '#ededed')
	stitchImages(im, outim).show()
	console.hide_activity()
	outim.save('image.jpg')
	console.quicklook('image.jpg')
	mode = console.alert("Image2ASCII", "You can either:","Share Text","Share Image")
	if mode == 1:
		file = open('output.txt', 'w')
		file.write(out)
		file.close()
		console.open_in('output.txt')
	elif mode == 2:
		console.open_in('image.jpg')
	time.sleep(5)
	console.clear()
コード例 #32
0
def cpoint(loc=""):
    loc = loc.replace("./", "")
    while 1:
        console.write_link("msf", "")
        if loc == "":
            sys.stdout.write(" ")
        else:
            loco = loc.split("/")
            sys.stdout.write(" %s(" % (loco[0]))
            console.set_color(1, 0, 0)
            sys.stdout.write("%s" % (loco[1]))
            console.set_color(1, 1, 1)
            sys.stdout.write(") ")
        try:
            data = raw_input("> ")
        except:
            print
            data = ""
            pass
        if data == "clear":
            console.clear()
        if data.startswith("use ") and len(data) > 4:
            data = data[4:]
            if data in sets:
                try:
                    cpoint(fdir(sets[data]))
                except:
                    pass
            else:
                try:
                    cpoint(fdir(data))
                except:
                    pass
        if data == "back":
            break
        if data == "exit":
            exit()
        if data == "banner":
            unilogo()
        meta_help(data, loc)
        if data.startswith("size ") and len(data) > 4:
            data = data[4:]
            try:
                console.set_font("Menlo", int(data))
            except:
                pass
        if data == "size":
            console.set_font("Menlo", 9.5)
        if data.startswith("remove ") and len(data) > 6:
            data = data[7:]
            try:
                if data in sets:
                    t = data + " => " + sets.get(data)
                    sets.pop(data)
                    var.remove(t)
                    print "Removed Values For \"%s\"" % data
            except Exception as e:
                print e
                pass
コード例 #33
0
def select_photos():
    console.clear()
    back = MyView(frame=(0, 0, 500, 500))
    back.present('sheet')
    todels = photos.pick_image(include_metadata=True,
                               original=True,
                               raw_data=False,
                               multi=True)
コード例 #34
0
def loop():
    while not done:
        data = multipeer.get_data()
        if data is not None:
            clear()
            print(data)
            print("> ", end="")
        sleep(0.2)
コード例 #35
0
def print_banner():
    console.clear()
    console.set_color(1, 0, 0)
    console.set_font("Menlo-Bold", 30)
    print("Insta Fortune!", end="")
    print("=" * 14)
    console.set_color(1, 1, 1)
    console.set_font()
コード例 #36
0
def clear():
    if os.name == 'nt': 
        os.system('cls')
    elif os.name == 'posix':
    		import console
    		console.clear() 
    else: 
        os.system('clear')
コード例 #37
0
def main():
    set_img = photos.pick_image()
    photos.save_image(set_img)
    console.clear()
    print "Generating image..."
    console.show_activity()
    sketch(set_img).show()
    console.hide_activity()
def test_install_from_github():
    console.clear()
    print("*** Testing Module Functions from: install_from_github.py ***\n")
    install_path = init_install_path(c.install_dir_name)
    url = make_git_url(c.git_usr, c.git_repo, c.git_branch)
    installed_files = install_from_github(install_path, GIT_AUTH, url)
    print(f"Installed the following files from: {url} ")
    pprint(installed_files)
コード例 #39
0
def main():
	set_img = photos.pick_image()
	photos.save_image(set_img)
	console.clear()
	print "Generating image..."
	console.show_activity()
	sketch(set_img).show()
	console.hide_activity()
コード例 #40
0
def main():
    global back, couleurs, grids, thumbs

    #----- Main code ------------------------
    console.clear()

    grids = [
        '1', '12', '1/2', '123', '11/23', '12/33', '1/2/3', '12/32', '12/13',
        '1234', '111/234', '12/34', '123/444', '11/22/34', '12/33/44',
        '11/23/44', '1/2/3/4', '12/13/14', '12/32/42', '11/23/43', '123/143',
        '123/425', '1234/5678/9abc/defg', '12345/67890/abcde/fghij/klmno'
    ]  #, '5', '1/4', '4/1', '2/3', f'3/2', '1/1/3', '1/3/1', '2/1/2', '2/2/1', '1/2/2', '3/1/1','1/1/1/2', '1/1/2/1', '1/2/1/1', '2/1/1/1', '1/1/1/1/1']

    couleurs = [
        'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige',
        'bisque', 'blanchedalmond', 'burlywood', 'cadetblue', 'chartreuse',
        'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan',
        'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue',
        'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
        'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow',
        'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki',
        'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue',
        'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray',
        'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen',
        'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue',
        'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
        'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
        'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
        'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
        'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
        'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
        'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
        'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
        'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
        'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
        'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
        'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
        'whitesmoke', 'yellow', 'yellowgreen', 'black', 'blue', 'blueviolet',
        'brown', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
        'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen',
        'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen',
        'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise',
        'darkviolet'
    ]
    # Sort colors on HSL H=Hue(teinte) S=Saturation L=Lightness(luminosité)
    couleurs = sorted(couleurs,
                      key=lambda x: colorsys.rgb_to_hsv(
                          ImageColor.getrgb(x)[0],
                          ImageColor.getrgb(x)[1],
                          ImageColor.getrgb(x)[2]))

    w, h = ui.get_screen_size()
    disp = 'full_screen'
    back = MyView(w, h)
    back.background_color = 'white'
    back.present(disp, hide_title_bar=True)

    thumbs = {}
コード例 #41
0
def backup(path=backpath, dst=dstpath):
    now = datetime.datetime.now()
    ymd = now.strftime('%Y-%m-%d')
    number = 1
    if not os.path.exists(dstpath):
        os.makedirs(dstpath)
    while True:
        basename = 'Backup' + ymd + '_' + str(number) + '.zip'
        zipFilename = os.path.join(dst + basename)
        if not os.path.exists(zipFilename):
            break
        number += 1
    a, b = 0, 0
    for f in os.listdir(path):
        if os.path.isdir(path + f):
            a += 1
        else:
            b += 1
    dispath = path.replace(os.path.expanduser('~'), '~')
    console.alert('备份{}'.format(dispath), '{}个文件夹和{}个文件,可能需要几秒钟'.format(a, b),
                  '确定')
    backupzip = zipfile.ZipFile(zipFilename, 'w')
    n = 1
    for foldername, subfolders, filenames in os.walk(path):
        #console.hud_alert('备份第{}个文件夹'.format(n), '1')
        if Trashpath in foldername and EXCLUDE_Trash:
            continue
        #print('备份第{}个子文件夹:{}'.format(n,foldername.replace(os.path.expanduser('~'),'~'))+'\n')
        backupzip.write(foldername)
        n += 1
        for filename in filenames:
            if filename.startswith('Backup') and filename.endswith('.zip'):
                continue
            backupzip.write(os.path.join(foldername, filename))
    backupzip.close()
    console.hud_alert('备份完成!开始进行HTTP服务器部署...', '3')

    os.chdir(dstpath)
    local_url = 'http://localhost:{}/{}'.format(PORT,
                                                os.path.basename(zipFilename))
    wifi_url = 'http://{}:{}/{}'.format(get_ip_address(), PORT,
                                        os.path.basename(zipFilename))
    server = HTTPServer(('', PORT), SimpleHTTPRequestHandler)
    console.clear()
    print('① 点击下面链接选择在Safari打开备份文件,再分享到其他App:')
    console.set_color(0, 0, 1)
    console.write_link(local_url + '\n', 'safari-' + local_url)
    console.set_color(1, 1, 1)
    print('\n② 如果想在局域网中其他设备访问该备份,请在其他设备中输入以下链接:')
    print(wifi_url)
    print('\n====\n完成分享后请在 console 中点停止.')
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.shutdown()
        server.socket.close()
        print('服务器终止')
コード例 #42
0
ファイル: dropboxlogin.py プロジェクト: c0ns0le/Pythonista
def get_request_token():
	console.clear()
	print 'Getting request token...'	
	sess = session.DropboxSession(app_key, app_secret, access_type)
	request_token = sess.obtain_request_token()
	url = sess.build_authorize_url(request_token)
	console.clear()
	webbrowser.open(url, modal=True)
	return request_token
コード例 #43
0
ファイル: debug.py プロジェクト: gilsim12/pcbasic
def bluescreen(e):
    """ Display a modal exception message. """
    state.console_state.screen.screen(0, 0, 0, 0, new_width=80)
    console.clear()
    console.init_mode()
    exc_type, exc_value, exc_traceback = sys.exc_info()
    # log the standard python error
    logging.error(''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)))
    # format the error more readably on the screen
    state.console_state.screen.set_border(4)
    state.console_state.screen.set_attr(0x70)
    console.write_line('EXCEPTION')
    state.console_state.screen.set_attr(15)
    if state.basic_state.run_mode:
        state.basic_state.bytecode.seek(-1, 1)
        program.edit(program.get_line_number(state.basic_state.bytecode.tell()),
                                         state.basic_state.bytecode.tell())
        console.write_line('\n')
    else:
        state.basic_state.direct_line.seek(0)
        console.write_line(str(tokenise.detokenise_compound_statement(state.basic_state.direct_line)[0])+'\n')
    stack = traceback.extract_tb(exc_traceback)
    for s in stack[-4:]:
        stack_line = '{0}:{1}, {2}'.format(
            os.path.split(s[0])[-1], s[1], s[2])
        stack_line_2 = '    {0}'.format(s[3])
        state.console_state.screen.set_attr(15)
        console.write_line(stack_line)
        state.console_state.screen.set_attr(7)
        console.write_line(stack_line_2)
    exc_message = traceback.format_exception_only(exc_type, exc_value)[0]
    state.console_state.screen.set_attr(15)
    console.write('{0}:'.format(exc_type.__name__))
    state.console_state.screen.set_attr(7)
    console.write_line(' {0}'.format(str(exc_value)))
    state.console_state.screen.set_attr(0x70)
    console.write_line(
        '\nThis is a bug in PC-BASIC.')
    state.console_state.screen.set_attr(7)
    console.write(
        'Sorry about that. Please send the above messages to the bugs forum\nby e-mail to ')
    state.console_state.screen.set_attr(15)
    console.write(
        '*****@*****.**')
    state.console_state.screen.set_attr(7)
    console.write(
        ' or by filing a bug\nreport at ')
    state.console_state.screen.set_attr(15)
    console.write(
        'https://github.com/robhagemans/pcbasic/issues')
    state.console_state.screen.set_attr(7)
    console.write_line(
        '. Please include')
    console.write_line('as much information as you can about what you were doing and how this happened.')
    console.write_line('Thank you!')
    state.console_state.screen.set_attr(7)
    flow.set_pointer(False)
コード例 #44
0
ファイル: dropboxlogin.py プロジェクト: cclauss/Pythonista-4
def get_request_token():
	console.clear()
	print('Getting request token...')	
	sess = session.DropboxSession(app_key, app_secret, access_type)
	request_token = sess.obtain_request_token()
	url = sess.build_authorize_url(request_token)
	console.clear()
	webbrowser.open(url, modal=True)
	return request_token
コード例 #45
0
ファイル: save_script.py プロジェクト: froggercat/Save-Script
def main():
    text = clipboard.get()
    assert text, 'No text on the clipboard!'
    filename = sys.argv[1]
    console.clear()
    print('Wait a Moment Please!')
    filename = save(filename, text)
    console.set_font('Futura', 16)
    print('Done!\nFile Saved as:\n' + filename)
コード例 #46
0
ファイル: game.py プロジェクト: Conair94/Blackjack
def hit():
	player_hand.insert(0,deck[0])
	deck.remove(player_hand[0])
	console.clear()
	print('Dealer has '+str(dealer_hand[0]))
	print('')
	print('You drew a '+ str(player_hand[0]))
	print(player_hand)
	print('')
コード例 #47
0
def main():
	console.clear()
	
	# Hide script
	w, h = ui.get_screen_size()
	disp = 'full_screen'
	back = MyView(w, h)
	back.background_color='white'
	back.present(disp, hide_title_bar=False)
	back.process()
コード例 #48
0
ファイル: tests.py プロジェクト: CodeSturgeon/mazin
def main():
    try:
        import console
        console.clear()
    except ImportError:
        pass

    grid = Grid(4, 4)
    print grid
    unittest.main()
コード例 #49
0
ファイル: WeatherAnywhere.py プロジェクト: c0ns0le/Pythonista
def main():
  console.clear()
  w, f = pick_your_weather()

  # Get array of weather icons
  icons = get_console_icons(w, f, icon_path)

  print('='*20)

  # Print current conditions to console
  try:
    # Open, resize & show icon for current weather, which is 1st one in array
    img = Image.open(icons[0]).resize((25, 25), Image.ANTIALIAS)
    img.show()
  except:
    missing_icons.append(icons[0])

  print(get_current_weather(w, f))
  #print(get_forecast(w, f))
  #sys.exit()

  '''
  Printing the extended forecast to the console
  involves a bit more code because we are inserting
  a weather icon at each blank line.
  '''
  extended_f = get_forecast(w, f).split('\n')
  '''
  Start getting icons from element 1, as we already
  used element 0 for current weather.
  '''
  count = 1
  for line in extended_f:
    # Look for blank lines
    if not line and count <= 20:
      ico = icons[count]
      try:
        # Open, resize and show weather icon
        img = Image.open(ico).resize((25, 25), Image.ANTIALIAS)
        img.show()
      except:
        missing_icons.append(ico)
      count += 1
    print line

  print '\nWeather information provided by api.wunderground.com'

  if missing_icons:
    ans = console.alert('Weather Icon(s) Missing:','','Download Them Now')
    if ans == 1:
      download_weather_icons(icon_path)

  alerts = get_alerts(w, f)
  if len(alerts) != 0:
    print alerts
コード例 #50
0
 def _get_request_token(self):
     console.clear()
     print 'Getting request token...'
     url = self.api.auth_user_get_url()
     console.clear()
     wv = ui.WebView()
     wv.load_url(url)
     wv.present()
     wv.wait_modal()
     purl = str(wv.eval_js("window.location.href"))
     return purl
コード例 #51
0
ファイル: SoundcloudDL2.py プロジェクト: c0ns0le/Pythonista
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)
コード例 #52
0
ファイル: SAT_Calc.py プロジェクト: kmaiya/mySATCalc
def menu1():
	print 'What would you like to do?\n'
	print 'Login(l)\nQuit(q)\n'
	inp = raw_input().lower()
	if inp == 'q':
		console.clear()
		print 'Thank you for using mySATCalc'
		sys.exit()
	elif inp == 'l':
		user = initProgram()
		menu2(user)
	else: 
		menu1()
コード例 #53
0
 def _get_request_token(self):
     console.clear()
     print 'Getting request token...'
     sess = session.DropboxSession(
         self.app_key, self.app_secret, self.access_type)
     request_token = sess.obtain_request_token()
     url = sess.build_authorize_url(request_token)
     console.clear()
     v = ui.WebView()
     v.load_url(url)
     v.present()
     v.wait_modal()
     return request_token
コード例 #54
0
ファイル: Screenshots.py プロジェクト: relic7/prodimages
def main():
		console.clear()
		print "Generating image..."
		console.show_activity()

		_1 = im1.resize((366,650),Image.ANTIALIAS)
		_2 = im2.resize((366,650),Image.ANTIALIAS)
		background.paste(_1,(0,0))
		background.paste(_2,(380,0))
		background.show()
		console.hide_activity()

		clipboard.set_image(background, format='jpeg', jpeg_quality=0.80)
		print "\n\n Image set to clipboard"
コード例 #55
0
ファイル: save_script.py プロジェクト: c0ns0le/Pythonista
def main():
	resp = console.alert('Alert!', 'Choose File Extension', '.py', '.pyui', hide_cancel_button=False)
	if resp==1:
		ext = '.py'
	elif resp==2:
		ext = '.pyui'
	text = clipboard.get()
	assert text, 'No text on the clipboard!'
	filename = sys.argv[1]
	console.clear()
	print('Wait a Moment Please!')
	filename = save(filename, text, ext)
	console.set_font('Futura', 16)
	print('Done!\nFile Saved as:\n' + filename)
コード例 #56
0
ファイル: open_in.py プロジェクト: c0ns0le/Pythonista
def main():
    resp = console.alert('Alert!', 'Choose File Extension', '.py', '.pyui', 'other', hide_cancel_button=False)
    if resp==1:
        ext = '.py'
    elif resp==2:
        ext = '.pyui'
    elif resp==3:
        ext = console.input_alert('Specify file extension')
    text = clipboard.get()
    assert text, 'No text on the clipboard!'
    filename = sys.argv[1]
    console.clear()
    filename = save(filename, text, ext)
    editor.open_file(filename)
コード例 #57
0
def main():
	if appex.is_widget():
		console.clear()
		v = appex.get_widget_view()
		# Check if the counter view already exists, if not, create it,
		# and set it as the widget's view.
		if not v or v.name != 'TallyCounter':
			v = make_widget_view()
			appex.set_widget_view(v)
	else:
		v = make_widget_view()
		v.name = 'Widget Preview'
		v.background_color = '#333'
		v.present('sheet')
コード例 #58
0
def main():
  """ 
	  	This starts the application.
	  	Arguments: 
	  	Specifics:
	""" 
  console.clear()
#//--------------------------------------------------------------
#//--------------- Global Variables -----------------------------
  #global 
  try:
    objCharacterManagement = clsCharacterManagement(True)
    objCharacterManagement.present_view()
  except:
	  pass
コード例 #59
0
def main():
	if appex.is_widget():
		console.clear()
		v = appex.get_widget_view()
		# Check if the clipboard view already exists, if not, create it,
		# and set it as the widget's view.
		if not v or v.name != 'Clipboard':
			v = make_widget_view()
		appex.set_widget_view(v)
	else:
		v = make_widget_view()
		v.background_color = '#333'
		v.name = 'Widget Preview'
		v.present('sheet')
	v['text_label'].text = 'Clipboard: ' + (clipboard.get() or '(Empty)')
コード例 #60
0
def main():

    # Attempt to take a URL from the arguments
    the_url = None
    try:
        the_url = sys.argv[1]
    except IndexError:
        # no arguments, use the clipboard contents
        the_url = clipboard.get()

    if not the_url:
        print repr(sys.argv)
        return

    console.clear()
    transfer_file(the_url)