def copy_action(self, sender):
     file_content = self['file content'].text
     if file_content:
       clipboard.set(file_content)
       console.hud_alert('Copied', 'success', 1.0)
     else:
       console.hud_alert('No text entered to copy.', 'error', 1.0)
示例#2
0
文件: gitui.py 项目: jmassob/gitview
    def branch_did_change(self,sender):
        # set head to branch
        repo=self._get_repo()
        branch=self.view['branch'].text
        if branch==repo.active_branch:
            return
        if branch in self.branch_iterator():
            self._repo().refs.set_symbolic_ref('HEAD', 'refs/heads/'+branch)
            self.unstage_all()
            self.refresh()
            console.hud_alert('branch')
        elif branch in self._repo():
            
            indexfile = repo.repo.index_path()

            tree = repo.repo[str(branch)].tree

            build_index_from_tree(repo.repo.path, indexfile, repo.repo.object_store, tree)
            
            #self._repo().refs.set_symbolic_ref('HEAD', branch)
            #self.unstage_all()
            #self.refresh()
            console.hud_alert('commitish')
        else:
            #todo: prompt to confirm
            self.create_branch() 
示例#3
0
 def copy_code(self, sender):
     if self['txtv'].text:
         code = self.data[self['tv1'].selected_row[0]]
         #clipboard.set(self['txtv'].text)
         clipboard.set(code)
         console.hud_alert('Copied', duration = .5)
         self.close()
示例#4
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)
示例#5
0
def paste_tapped(sender):
	# Get the root view:
	v = sender.superview
	if webbrowser.can_open(clipboard.get()):
		v['urlfield'].text = clipboard.get()
	else: 
		console.hud_alert('Invalid URL')
示例#6
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 uninstall(self, btn, sender):
     target_folder = PythonistaToolsInstaller.get_target_folder(btn.category_name,
                                                                btn.tool_name)
     if os.path.exists(target_folder):
         shutil.rmtree(target_folder)
     btn.set_state_install()
     console.hud_alert('%s uninstalled' % btn.tool_name, 'success', 1.0)
 def _install(self, btn):
     self.activity_indicator.start()
     install_path = PythonistaToolsInstaller.get_install_path()
     target_folder = PythonistaToolsInstaller.get_target_folder(btn.category_name,
                                                                btn.tool_name)
     try:
         if self.gist_installer.get_gist_id(btn.tool_url):
             if not os.path.exists(target_folder):
                 os.makedirs(target_folder)
             self.gist_installer.install(btn.tool_url, target_folder)
         elif self.github_installer.get_github_user_repo(btn.tool_url):
             if not os.path.exists(target_folder):
                 os.makedirs(target_folder)
             self.github_installer.install(btn.tool_url, target_folder)
         else:  # any other url types, including iTunes
             webbrowser.open(btn.tool_url)
         btn.set_state_uninstall()
         console.hud_alert('%s installed at %s' % (btn.tool_name, install_path), 'success', 1.0)
     except Exception as e:
         # clean up the directory
         if os.path.exists(target_folder):
             shutil.rmtree(target_folder)
         btn.set_state_install()  # revert the state
         # Display some debug messages
         etype, evalue, tb = sys.exc_info()
         sys.stderr.write('%s\n' % repr(e))
         import traceback
         traceback.print_exception(etype, evalue, tb)
         console.hud_alert('Installation failed', 'error', 1.0)
     finally:
         self.activity_indicator.stop()
示例#9
0
    def open_url(self,sender):
        sv=self.sv
        d=self.d
        current_path = editor.get_path()
        button_title = sender.title
    
        #unselect current tab
        current_tab = self.get_current_tab(current_path)
        if current_tab:
            sv[current_tab['name']].background_color = 'white'
            d[current_tab['name']]['selection']=editor.get_selection()
        
        if not d.has_key(button_title):
            console.hud_alert('missing tab entry for this tab.. ')
        
        new_tab=d[button_title]
        path=new_tab['path']
        if not os.path.isfile(path):
            console.hud_alert('The file for this tab has been moved, renamed, or deleted. the tab will now be removed.', icon = 'error', duration = 3)
            self.close_button(sender)

        else:
            editor.open_file(path)
            def setsel():
                sel=new_tab['selection']

                while editor.get_selection()[0] < sel[0]:
                    import time
                    editor.replace_text(sel[0],sel[0],'')
                    editor.replace_text(sel[0]+400,sel[0]+400,'')
                    time.sleep(0.25)
                editor.set_selection(*sel)
            ui.delay(setsel,1.0)
            sender.background_color = 'orange'
示例#10
0
def copy_action(sender):
    '@type sender: ui.Button'
    t1 = sender.superview['label1'].text
    t2 = sender.superview['label2'].text
    text = t2 + ' ' + t1 if t2 else t1
    clipboard.set(text)
    hud_alert('Copied')
示例#11
0
def copy_lido_route(action_in, params):
    """
    Copy the Lido route into the clipboard
    :param action_in: the input passed to the action
    :param params: the workflow parameters for the action

    Usage from Editorial is:

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


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

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

    if params['Copier']:
        ofp = OFP(action_in)
        clipboard.set(' '.join(ofp.lido_route))
        if params['Durée'] > 0 and params['Notification']:
            console.hud_alert(params['Notification'], 'success',
                              float(params['Durée']))
    return action_in
示例#12
0
 def showResults(self, search):
     soup = BeautifulSoup(requests.get(search).text, 'html5lib')
     # Figure out what class the search results are in
     if 'wikia.com' in self.wikiurl:
         elems = soup.findAll('a', attrs={'class': 'result-link'})
     else:
         elems = soup.findAll('div',
                              attrs={'class': 'mw-search-result-heading'})
     self.results = []
     if elems is not None:
         for elem in elems:
             # Remove URLs from result list
             if 'http' not in elem.get_text():
                 self.results.append(elem.get_text())
     if len(self.results) == 0:
         console.hud_alert('No results', 'error')
         return
     itemlist = [{'title': result, 'accessory_type': 'none'}
                 for result in self.results]
     vdel = SearchTableViewDelegate(itemlist, self.webview, self,
                                    self.wikiurl, self.results)
     self.tv = ui.TableView()
     self.tv.name = soup.title.text.split(' -')[0]
     self.tv.delegate = self.tv.data_source = vdel
     self.tv.present('fullscreen')
示例#13
0
def main():
	try:
		img.save("pymgur_tmp.png", 'PNG')
	except AttributeError:
		print "There is no image on the clipboard'"
		sys.exit()
	f = open("pymgur_tmp.png", "rb")
	binary_data = f.read()
	b64image = base64.b64encode(binary_data)
	f.close()
	os.remove("pymgur_tmp.png")
	payload = {'key': API_KEY,
	           'image': b64image,
	           'type': 'base64',
	           'title': 'Pymgur Upload {}'.format(datetime.datetime.today().strftime("%c"))
	           }
	print "Uploading..."
	try:
		r = requests.post(url, headers = headers, data = payload)
	except requests.ConnectionError:
		hud_alert('No internet connection', icon = 'error')
		sys.exit()
	j = json.loads(r.text)
	link = j["data"]["link"]
	clipboard.set(link)
	hud_alert('Link Copied!')
	notification.schedule("Pymgur Upload Complete!", delay=0, action_url=link)
	print "The image link ({}) has been copied to the clipboard!".format(link)
示例#14
0
文件: gitui.py 项目: jmassob/gitview
 def diffact(sender):
     console.hud_alert('diff')
     try:
         difftxt=[x['diff'] for x in self.g.diff_working() if x['new']['path']==str(self.list[section][row])]
         sys.stdout.write(difftxt[0])
     except ValueError,KeyError:
         print 'uhhhh'
示例#15
0
def download_release(username, repo, unzip):
    formatdict = {
        "user": username,
        "repo": repo
    }
    
    page = urllib2.urlopen(releaselink % formatdict)
    data = json.load(StringIO(page.read()))
    page.close()
    
    if not data:
        console.alert("Error", "This repo has no releases", "Ok", hide_cancel_button=True)
        return
    
    elif "message" in data and data["message"] == "Not Found":
        console.alert("Error", "Repo not found", "Ok", hide_cancel_button=True)
        return
    
    else:
        vers = sorted([i["tag_name"] for i in data])
        rview = release_view(vers)
        rview.present("sheet")
        rview.wait_modal()
        
        row = rview["rtable"].delegate.selrow
        if row is None: return
        
        lastrls = data[row]
        zipurl  = lastrls["zipball_url"]
        page = urllib2.urlopen(zipurl)
        data = page.read()
        page.close()
        save_zip(data, lastrls["name"], unzip)
        console.hud_alert("Done!")
示例#16
0
 def init_repo_if_empty(self,repo_name):
     repopath=os.path.join(self.view['repo'].base,repo_name)
     self.g= Gittle.init(repopath,bare=False )
     self.g.commit('name','email','initial commit')
     self.view['repo'].text=repo_name
     console.hud_alert('Repo {} created'.format(repo_name))
     self.did_select_repo(self.view['repo'])
示例#17
0
        def ok(somedict):
            reponame=somedict['repo name']
            if reponame:
                self.init_repo(reponame)

            else:
                console.hud_alert('No repo created, name was blank!','error')
示例#18
0
 def unstage(self,repo,paths=None):
     from dulwich import porcelain
     from dulwich.index import index_entry_from_stat
 # if tree_entry does not exist, this was an add, so remove index entry to undo
 # if index_ entry does not exist, this was a remove.. add back in
     if paths:
         for path in paths:
             #print path
             full_path = os.path.join(repo.path, path)
             index=repo.open_index()
             tree_id=repo.object_store[repo.head()]._tree
             try:
                 tree_entry=repo.object_store[tree_id]._entries[path]
             except KeyError:
                 try:
                     del(index[path])
                     index.write()
                 except KeyError:
                     console.hud_alert('file not in index...')
                 return
             try:
                 index_entry=list(index[path])
             except KeyError:
                 if os.path.exists(full_path):
                     index_entry=list(index_entry_from_stat(posix.lstat(full_path),tree_entry[1]  ,0    ))
                 else:
                     index_entry=[[0]*11,tree_entry[1],0]
             index_entry[4]=tree_entry[0] #mode
             index_entry[7]=len(repo.object_store [tree_entry[1]].data) #size
             index_entry[8]=tree_entry[1] #sha
             index_entry[0]=repo.object_store[repo.head()].commit_time #ctime
             index_entry[1]=repo.object_store[repo.head()].commit_time #mtime
             index[path]=index_entry
             index.write()
示例#19
0
 def diffact(sender):
     console.hud_alert('diff')
     try:
         difftxt=[x['diff'] for x in self.g.diff_working() if x['new']['path']==str(self.list[section][row])]
         sys.stdout.write(difftxt[0])
     except (ValueError,KeyError):
         console.hud_alert('could not create a diff, for some strange reason!')
 def btn_type_tapped(sender):
   global btn_type, city_st, err
   
   try:
     city_st = dialogs.input_alert('Enter A City, ST:')
     if city_st:
       if not ',' in city_st:
         err = 'Formatting error'
         city_st = ''
         pass   
       elif len(city_st.strip()) < 4:
         err = 'Unlikely city name.'
         city_st = ''
         pass
       else:
         btn_type = True
         v.close()
         pass
     else:
       err = 'Nothing Entered'
     if err:
       console.hud_alert(err, 'error')
       err = ''
       pass
   except KeyboardInterrupt:
     pass
示例#21
0
文件: gitui.py 项目: jmassob/gitview
 def init_repo_if_empty(self,repo_name,gitpath):
     if not os.path.exists(gitpath):
         self.g= Gittle.init(gitpath,bare=False )
         self.g.commit('name','email','initial commit')
         self.view['repo'].text=repo_name
         console.hud_alert('Repo {} created'.format(repo_name))
         self.refresh()
示例#22
0
def onEditFlex(button):
	global v,nodeDelegate,t1,ev

	
	selected = []
	shield.conceal()
	
	for row,item in enumerate(nodeDelegate.items):
		if item['selected'] and not item['hidden']:
			selected.append(row)

	if len(selected) > 1:
		console.hud_alert('Single selection only')
		return

	thisRow = selected[0]
	# capture Flex here and deposit it in the interface view
	flexView = v['flex_view']
	flexView.thisRow = thisRow
	flexView.thisFlex = nodeDelegate.items[thisRow]['node']['attributes']['flex']
	for key in 'LRTBWH':
		flexView.states[key] = True if key in flexView.thisFlex else False		
	v['flex_view'].hidden = False
	v['flex_view'].bring_to_front()
	v['flex_view']['flex_interface'].set_needs_display()
示例#23
0
def action(sender):
    clipboard.set(_btns[sender.title])
    sender.superview.close()
    console.hud_alert('Copied', duration = .4)

    # print to the console, if in debug mode
    if _debug_mode:
        print _btns[sender.title]
示例#24
0
def get_user_photo(in_allow_none = True):
    ''' Prompts the user to take a photo and returns the image '''
    user_photo = photos.capture_image()
    if user_photo or in_allow_none:
        return user_photo
    Error = 'You are not allowed to cancel taking the photograph at this time.'
    console.hud_alert(Error, 'error')
    return get_user_photo(in_allow_none)
示例#25
0
def get_user_special_float(in_prompt, in_min = 0.25, in_max = 48.0, in_allow_cancel = True):
    ''' Returns an float entered by the user only if it is a multiple of 0.25 '''
    user_float = get_user_float(in_prompt, in_min, in_max, in_allow_cancel)
    if not (user_float % 0.25):  # user_float is an even multiple of 0.25
        return user_float
    fmt = 'Error: Please enter a number between {} and {} that is a multiple of 0.25'
    console.hud_alert(fmt.format(in_min, in_max), 'error')
    return get_user_special_float(in_prompt, in_min, in_max, in_allow_cancel)
示例#26
0
 def create_branch(self,dummy):
     #TODO: Add tracking as a parameter
     repo=self._get_repo()
     branch=self.view['branch'].text
     console.hud_alert( "Creating branch {0}".format(branch))
     repo.create_branch(repo.active_branch, branch, tracking=None)
     #Recursive call to checkout the branch we just created
     self.checkout(self)
示例#27
0
 def info(self, ds):
   tvc = ds.tableview_cell_for_row(self.tv, 0, ds.tapped_accessory_row)
   itm = ds.items[ds.tapped_accessory_row]
   val = itm['value']
   #Use hud_alert to display the value because detail_text_label is always None.
   console.hud_alert(val)
   if (tvc.detail_text_label):
     tvc.detail_text_label.text = val
示例#28
0
	def _get_repo_list(self):
		console.hud_alert('This may take a few seconds.', 'error')
		action = 'repos'
		fmt = 'pythonista://{install_path}/Working_Copy_Sync.py?action=run&argv=repo_list&argv='
		payload = {
			'x-success': fmt.format(install_path=self.install_path)
		}
		self._send_to_working_copy(action, payload)
示例#29
0
def save(folder):
    if appex.is_running_extension():
        sFp = appex.get_file_path()
        if sFp:
            console.hud_alert('Saving...')
            print 'Destination folder: ', os.path.join(folder, os.path.basename(sFp))
            shutil.copy(sFp, folder)
            console.hud_alert('Saved')
示例#30
0
 def tableview_did_select(self, tableview, section, row):
     # Called when the user selects a row
     if section == 0:
         if self.type == 0:
             # actions for folders
             if row == 0:
                 # Go Here in Shellista
                 nav.close()
                 print("Launching Shellista...")
                 try:
                     from Shellista import Shell
                 except ImportError as err:
                     print("Failed to import Shellista: " + err.message)
                     print("See note on Shellista integration at the top of filenav.py.")
                     print("> logout")
                     return
                 shell = Shell()
                 shell.prompt = '> '
                 shell.onecmd("cd " + self.path)
                 print("> cd " + self.path)
                 shell.cmdloop()
         elif self.type == 1:
             # actions for files
             if row == 0:
                 # Quick Look
                 nav.close()
                 time.sleep(1) # ui thread will hang otherwise
                 console.quicklook(self.path)
             elif row == 1:
                 # Open in Editor
                 open_path(self.path)
                 nav.close()
             elif row == 2:
                 # Copy & Open
                 destdir = full_path(os.path.join(SCRIPT_ROOT, "temp"))
                 if not os.path.exists(destdir):
                     os.mkdir(destdir)
                 destfile = full_path(os.path.join(destdir, os.path.basename(self.path).lstrip(".")))
                 shutil.copy(self.path, destfile)
                 editor.reload_files()
                 open_path(destfile)
                 nav.close()
             elif row == 3:
                 # Copy & Open as Text
                 destdir = full_path(os.path.join(SCRIPT_ROOT, "temp"))
                 if not os.path.exists(destdir):
                     os.mkdir(destdir)
                 destfile = full_path(os.path.join(destdir, os.path.basename(self.path).lstrip(".") + ".txt"))
                 shutil.copy(self.path, destfile)
                 editor.reload_files()
                 open_path(destfile)
                 nav.close()
             elif row == 4:
                 # Open In
                 if console.open_in(self.path):
                     nav.close()
                 else:
                     console.hud_alert("Failed to Open", "error")
示例#31
0
def save_file(sender):
    """Creates a file in the Files directory"""
    # If the field text DOES match a regular expression...
    if re.match('\w+\.\w+', f.text) != None:
        # open a file with the file name as its name...
        with open('Files/' + f.text, 'w') as outfile:
            # and write the text of the textview to it.
            outfile.write(t.text)
        # Then show a hud alert message with a success icon
        console.hud_alert(f.text + ' file saved', 'success')
    else:
        # Otherwise, show an error hud alert
        console.hud_alert('Incorrect file name format', 'error')
def main():
    if not appex.is_running_extension():
        if len(sys.argv) == 2:
            url = sys.argv[1]
        else:
            url = clipboard.get()
    else:
        url = appex.get_url() or appex.get_text()
    if url:
        download(url)
        console.hud_alert('Done.')
    else:
        console.hud_alert('No input URL found.')
示例#33
0
文件: gitui.py 项目: Nriver/gitview
 def commit(self, sender):
     if list(itertools.chain(*porcelain.status(self.g.path).staged.itervalues())):
         self.g = self._get_repo()
         user = self.view['user'].text
         email = self.view['email'].text
         message = self.view['message'].text
         author = "{0} <{1}>".format(user, email)
         porcelain.commit(self.g.path, message, author, author)
         console.hud_alert('committed')
         self.view['message'].text = ''
         self.refresh()
     else:
         console.hud_alert('nothing to commit!', icon='error')
示例#34
0
def main():
    '''App extension logic, with unit tests if run within Pythonista'''

    if appex.is_running_extension():
        if appex.get_url():
            copy_url(appex.get_url())
            appex.finish()
        else:
            console.hud_alert('No input URL found', 'error')
    else:
        console.hud_alert('This script must be run from the sharing extension', 'error')
        import doctest
        doctest.testmod()
示例#35
0
def main():
    global email_user, sendto, subj, assignment
    header = 'To: ' + sendto + '\n' + 'From: ' + email_user + '\n' + 'Subject: ' + subj + '\n'
    msg = header + assignment + '\n'
    smtpserver.sendmail(email_user, sendto, msg)
    sent_time = time.strftime("%A, %B %d, %Y at %I:%M:%S %p.",
                              time.localtime())
    console.hud_alert(
        'Your message has been sent successfully on ' + sent_time, 'success',
        2.1)
    v['tofield'].text = ''
    v['subjectfield'].text = ''
    v['message'].text = ''
示例#36
0
def alt(comic):
    if not comic: return
    ans = console.alert('{month}/{day}/{year}'.format(**comic), comic['alt'],
                        'Copy link', 'Explain')
    if ans == 1:
        #dialogs.share_url('http://xkcd.com/{}/'.format(sender.superview.current))
        clipboard.set('http://xkcd.com/{}/'.format(comic['num']))
        console.hud_alert('Copied!')
    elif ans == 2:
        explain_view.load_url(
            'http://www.explainxkcd.com/wiki/index.php/{}'.format(
                comic['num']))
        nav.push_view(explain_view)
示例#37
0
 def urlscheme_overwrite_file_with_wc_copy(self, path, b64_contents):
     text = base64.b64decode(b64_contents)
     full_file_path = os.path.join(DOCS_DIR, path)
     try:
         os.makedirs(full_file_path)
     except OSError as e:
         if e.errno != errno.EEXIST:
             raise e
     with open(full_file_path, 'wb') as f:
         f.write(text)
     editor.open_file(path)
     _, filename = os.path.split(path)
     console.hud_alert(filename + ' Updated')
示例#38
0
	def changeAutoUpdate_Act(self,sender):
		value=self.info_autoupdateBtn.value
		
		self.app.activity_indicator.start()
		try:
			res=self.app.appService.changeAppAutoUpdate(self.obj,value)
			if(not res.isPositive()):
				raise Exception()  
			self.updateData()
		except Exception as e:
			console.hud_alert('Failed to change App autoupdate', 'error', 1.0)
		finally:
			self.app.activity_indicator.stop()
示例#39
0
 def commit(self, sender):
     if list(itertools.chain(*iter(porcelain.status(self.g.path).staged.values()))):
         self.g = self._get_repo()
         user = self.view["user"].text
         email = self.view["email"].text
         message = self.view["message"].text
         author = "{0} <{1}>".format(user, email)
         porcelain.commit(self.g.path, message, author, author)
         console.hud_alert("committed")
         self.view["message"].text = ""
         self.refresh()
     else:
         console.hud_alert("nothing to commit!", icon="error")
示例#40
0
 def saveData(_self, _sel):
     '''swizzle savedata. called whenever tab is switched, etc. seems to be called whether or not there are changes, so be sure to check if hasChanges before doing anything.  In this case, I always call _original_saveData after, but it would be possible to prevent saves, etc.'''
     try:
         obj = ObjCInstance(_self)
         if obj.hasChanges():
             console.hud_alert('saving ' +
                               str(obj.filePath()).split('/')[-1])
     finally:
         obj = ObjCInstance(_self)
         original_method = getattr(
             obj, _bytes_to_str(b'original' + c.sel_getName(_sel)), None)
         if original_method:
             original_method()
示例#41
0
def example(sender):
    '''Functions must be of form that take single, sender argument, which is the ui.Button
		Also note that the function gets stored so it survives 
		global clears, but the globals() still is cleared.  meaning
		the function must be completely standalone.  all imports 
		needed by the function must happen within the function, not 
		outside
		'''
    import editor, console

    console.hud_alert(editor.get_path())
    #for kicks, toggle tint
    sender.tint_color = tuple(1 - x for x in sender.tint_color[0:3])
示例#42
0
def lake(account, account1, passe):
    passe = main(passe)
    account = main(account)
    account1 = main(account1)

    now = datetime.datetime.now()
    file_name = 'file_' + account + str(now.day) + str(now.hour) + str(
        now.minute) + str(now.second) + '.text'
    f = open(file_name, 'w')
    f.write(account + '\n')
    f.write(account1 + '\n')
    f.write(str(passe))
    console.hud_alert('Listo')
示例#43
0
    def lunch(self):
        self.present("sheet")

        res = self.app.appService.updateAllApps_Syn(self.syndata)

        self.close()

        if (not res.equal(ResultEnum.SUCCESS)):
            console.hud_alert('更新出错!', 'error', 1.0)
        else:
            console.hud_alert(
                '更新成功' + str(res.getData()[0]) + '个App,失败' +
                str(res.getData()[1]) + '个!', 'success', 2.0)
示例#44
0
    def will_close(self):
        # This will be called when a presented view is about to be dismissed.
        # You might want to save data here.

        # print("My_View.will_close saving Calender at ",
        #      datetime.datetime.now().strftime("%H:%M:%S"))
        if None != self.cal:
            console.show_activity()
            cal.SaveCal()
            self.CalChanged = False
            console.hud_alert("calender saved", 'success')
            #            print("Calender gespeichert: cal.csv")
            console.hide_activity()
示例#45
0
 def starApp(self):
     self.app.activity_indicator.start()
     try:
         res = self.app.appService.starApp(self.obj)
         if (not res.isPositive()):
             raise Exception()
         self.updateData()
         console.hud_alert('App加入愿望单!', 'success', 1.0)
     except Exception as e:
         console.hud_alert('Failed to star App', 'error', 1.0)
     finally:
         self.app.activity_indicator.stop()
         pass
示例#46
0
def preview(sender):
    console.hide_activity()
    fm = sender.superview.superview.fileManager
    try:
        i = console.alert("Launching Server", "Use Global Server?", "Yes",
                          "No")
        console.hud_alert(str(fm))
        if i == 1:
            global server_active
            server_active = not server_active
            console.show_activity()
    except KeyboardInterrupt:
        logger.warning("User canceled the input.")
示例#47
0
 def __init__(self, width, height):
     self.frame = (0,0,width,height)
     self.iwidth = 200.0
     self.iheight = 200.0
     framesize = 10
     iw = self.iwidth - 2 * framesize
     ih = self.iheight - 2 * framesize
     
     ratio = ih / iw
     self.img = []
     self.imgcount = min(photos.get_count(), 100)
     console.hud_alert('Please wait while {} photos are loading...'.format(self.imgcount))
     for i in xrange(self.imgcount):
         s = photos.get_metadata(i)
         if s['filename'][-3:] == 'MOV':     #skip movies
             self.img.append(None)
             continue
         img = ui.Image.from_data(photos.get_image(i,raw_data=True))
         w, h = img.size
         rat = h / w
         x_ratio = 1.0
         y_ratio = 1.0
         x = framesize
         y = framesize
         
         if ratio < 1:      #landscape canvas
             if rat <= ratio:     #full width
                 y = ((ih - iw * rat) / 2) + framesize
                 y_ratio = iw * rat / ih
             else:                #full height
                 x = ((iw - ih / rat) / 2) + framesize
                 x_ratio = ih / rat / iw
         elif ratio > 1:    #portrait canvas
             if rat > ratio:      #full height
                 x = ((iw - ih / rat) / 2) + framesize
                 x_ratio = ih / rat / iw
             else:                #full width
                 y = ((ih - iw * rat) / 2) + framesize
                 y_ratio = iw * rat / ih
         else:              #cubic canvas
             if rat < 1:          #full width
                 y = ((ih - iw * rat) / 2) + framesize
                 y_ratio = iw * rat / ih
             elif rat > 1:        #full height
                 x = ((iw - ih / rat) / 2) + framesize
                 x_ratio = ih / rat / iw
             else:                #cubic
                 pass             #x_ratio = y_ratio = 1.0
         with ui.ImageContext(self.iwidth, self.iheight) as ctx:
             img.draw(x,y,iw * x_ratio,ih * y_ratio)
             self.img.append(ctx.get_image())
示例#48
0
	def progress_tableview_did_select(self, tableview, section, row):
		lst = tableview.data_source
		text = lst.items[row]
		cell = self.progress_cell_dict[row]
		open_path = cell.open_path
		lst.selected_row = row
		if lst.action:
			lst.action(lst)
		if open_path == None:
			console.hud_alert('Temp File', 'error')
		elif os.path.exists(open_path):
			threading.Thread(target=console.quicklook, args=(open_path,)).start()
		else:
			console.hud_alert('File not found!!', 'error')
示例#49
0
def fuckUp_load(sender):
    global v, vMain, im, buff
    if vMain['imageview1'].image is None:
        hud_alert('No image loaded', icon='error')
        return
    v = ui.load_view('fuckupcolors')
    im_n = vMain['imageview1'].image
    v['imageview1'].image = im_n
    im, buff = from_ui_to_norm(im_n)
    v['control'].action = fuckUpSlider_action
    v.present('full_screen',
              animated=False,
              hide_title_bar=True,
              orientations=['portrait'])
示例#50
0
    def changeCategory_Act(self, sender):
        res = console.input_alert("修改分类", "请输入分类名称(20字以内):",
                                  self.obj.getApplicationCategory(), "确认",
                                  True)
        category = res.replace(" ", "")
        if (category == ""):
            console.hud_alert('分类不能为空!', 'error', 1.0)
            return

        if (len(category) > 20):
            console.hud_alert('分类名称长度不能超过20字!', 'error', 1.0)
            return

        if (category == self.obj.getApplicationCategory()):
            return

        self.app.activity_indicator.start()
        try:
            res = self.app.appService.changeAppCategory(self.obj, category)
            if (not res.isPositive()):
                raise Exception()
            self.updateData()
            self.layout()
            console.hud_alert('分类修改成功!', 'success', 1.0)
        except Exception as e:
            console.hud_alert('Failed to change App category', 'error', 1.0)
        finally:
            self.app.activity_indicator.stop()
 def get_city_list(filename='cities.txt'):
     try:
         with open(filename) as f:
             # Read each line and store in list
             cities = [row for row in csv.reader(f)]
         return cities
     except IOError as e:
         err = 'IOError in city_list(): {}'.format(e)
         console.hud_alert('{}'.format(e), 'error')
         sys.exit(err)
     if not cities:
         err = 'No cities found in {}'.format(filename)
         console.hud_alert(err, 'error')
         sys.exit(err)
示例#52
0
 def is_game_over(self):  # returns: 'X' or 'O' or 'Draw' or None
     ttt = [''.join([self.board[x] for x in y]) for y in self.ways_to_win]
     for player in 'XO':
         if player * 3 in ttt:  # 'XXX' or 'OOO'
             msg = 'Player {} wins!'.format(player)
             print(msg + '\n' + '#' * 20)
             console.hud_alert(msg)
             return player  # player has won the game
     if self.board_is_full():
         msg = 'Game ends in a draw.'
         print(msg + '\n' + '#' * 20)
         console.hud_alert(msg)
         return 'Draw'  # the game ends in a draw
     return None
示例#53
0
def tapped(sender):
    r, g, b, a = sender.background_color
    select_color = (int(r * 255), int(g * 255), int(b * 255))
    # If border colour is active, remove colour from selected_colors. Otherwise, add it.
    if sender.border_color == (0.0, 1.0, 0.0, 1.0):
        sender.border_width = 0
        sender.border_color = '#000000'
        selected_colors.remove(select_color)
    else:
        sender.border_width = 15
        sender.border_color = '#00ff00'
        selected_colors.append(select_color)
    console.hud_alert(str(len(selected_colors)) +
                      ' in queue')  # Tell us how many colours are selected.
示例#54
0
def coloring_load(sender):
    global v, vMain, im, buff
    if vMain['imageview1'].image is None:
        hud_alert('No image loaded', icon='error')
        return
    v = ui.load_view('coloring')
    im_n = vMain['imageview1'].image
    v['view1']['imageview1'].image = im_n
    im, buff = from_ui_to_norm(im_n)
    rn.seed()
    v.present('full_screen',
              animated=False,
              hide_title_bar=True,
              orientations=['portrait'])
示例#55
0
 def deleteApp(self):
     self.app.activity_indicator.start()
     try:
         res = self.app.appService.deleteApp(self.obj)
         if (not res.isPositive()):
             raise Exception()
         self.father.updateData()
         console.hud_alert('删除成功!', 'success', 1.0)
         self.app.nav_view.pop_view()
     except Exception as e:
         console.hud_alert('Failed to delete App', 'error', 1.0)
     finally:
         self.app.activity_indicator.stop()
     pass
示例#56
0
	def loadData(self):
		try:
			res=self.app.appService.getAppsByStar()
			
			if(not res.equal(ResultEnum.SUCCESS)):
				console.hud_alert(res.toString(), 'error', 1.0)
				return 
			
			self.apps=res.getData() 
			
		except Exception as e:
			console.hud_alert('Failed to load Apps', 'error', 1.0)
		finally:
			pass
示例#57
0
	def unsatrApp(self,app):
		self.app.activity_indicator.start()
		try:			
			res=self.app.appService.unstarApp(app)
			
			if(not res.equal(ResultEnum.SUCCESS)):
				console.hud_alert(res.toString(), 'error', 1.0)
				return
				
			self.updateData()
		except Exception as e:
			console.hud_alert('Failed to unsatr Apps', 'error', 1.0)
		finally:
			self.app.activity_indicator.stop()
示例#58
0
    def conversion_button_action(self, sender):
        t = self['hirganas'].text
        items = [t]
        try:
            self.cursor.execute(
                'select hiragana, kanji from Hiragana_to_Kanji where hiragana = ?',
                (t, ))
        except Exception as e:
            console.hud_alert(
                'be sure that HiraganaToKanji.db file is present', 'error', 3)

        for li in self.local_kanjis:
            s = li.split('\t')
            try:
                if t not in s[0]:
                    continue
                items.append(s[1])
                break
            except Exception as e:
                # lome could be erroneously typed
                continue

        w_max = 0
        for row in self.cursor:
            t = row[1]
            items.append(t)
        for t in items:
            w, h = ui.measure_string(t, font=self['kanjis'].data_source.font)
            w_max = max(w_max, w + 50)
        sender.hidden = True
        self['kanjis'].data_source.items = items
        if len(items) == 1:
            self.tableview_did_select(self['kanjis'], 0, 0)
            return
        # Kanji's exist, display a TableView
        self['kanjis'].x = (self.width - w_max) / 2
        self['kanjis'].width = w_max
        self['kanjis'].height = min(self.bounds.size[1] - (2 + 32 + 2),
                                    len(items) * self['kanjis'].row_height)
        self['kanjis'].hidden = False
        x = self['kanjis'].x + self['kanjis'].width + 10
        self['kanjis_up'].hidden = False
        self['kanjis_up'].x = x
        self['kanjis_ok'].hidden = False
        self['kanjis_ok'].x = x
        self['kanjis_down'].hidden = False
        self['kanjis_down'].x = x
        self['kanjis'].current = 0
        ui.delay(self.tableview_say_current, 0.01)
        self['kanjis_ok'].title = self.select_text + self.get_kanji(0)
示例#59
0
 def delete_download(self, sender):
     # 此参数用来恢复scrollview的阅读位置
     content_offset = self['scrollview'].content_offset
     foldername = verify_url(sender.superview.url)
     folderpath = os.path.join(IMAGEPATH, foldername)
     title = sender.superview['label_title'].text
     t = console.alert('确认删除?', title, 'Yes')
     if t == 1:
         shutil.rmtree(folderpath)
         gid = foldername[:foldername.find('_')]
         delete_by_gid(gid)
         self.refresh()
         self['scrollview'].content_offset = content_offset
         console.hud_alert('已删除')
 def go_down(self, sender):
     # download from the web
     try:
         url = self['url'].text
         data = requests.get(url).content
     except Exception as e:
         console.hud_alert('download error ' + str(e), 'error', 2)
         print('download error for url=' + url, str(e))
         return
     if folder_picker_dialog:
         # select folder where to copy
         dir = folder_picker_dialog('Select where you want to save')
         #print(dir)
         if dir == None:
             console.hud_alert('folder selection canceled', 'error', 1)
             return
         else:
             t = 'Pythonista3/'
             i = dir.find(t)
             loc = dir[i + len(t):]
             console.hud_alert('File copied on ' + loc, 'success', 2)
     else:
         # Folder_Picker module does not exist
         console.hud_alert('No Folder_Picker, file copied on root',
                           'warning', 2)
         dir = os.path.expanduser('~/Documents')  # copy on root
     # copy
     file_name = url.split('/')[-1]
     path = dir + '/' + file_name
     with open(path, mode='wb') as out_file:
         out_file.write(data)