Exemplo n.º 1
0
 def populate_table(self):
     console.show_activity()
     if callable(self.items):
         items=self.items()
     else:
         items=self.items
         
     dropdownlist=[]
     self.listsource.items=dropdownlist
     self.tbl.reload()        
     for item in items:
       def ani():
         dropdownlist.append(item)
         offset=self.tbl.content_offset
         self.listsource.items=dropdownlist
         self.tbl.reload()
         try:
             self.listsource.selected_row = self.listsource.items.index(self.textfield.text)
             self.listsource.tableview.selected_row = (0,self.listsource.selected_row)
         except ValueError:
             #self.listsource.selected_row=-1
             self.listsource.tableview.selected_row=(0,-1)
         self.tbl.content_offset=tuple(offset)
       ui.animate(ani,0.1)
     console.hide_activity()
Exemplo n.º 2
0
def load_comic(view, num):
    if num == 404:
        #view['comic'].image = ui.Image('loading.png')
        view['wv'].load_url(os.path.abspath('loading.png'))
        view.current = num
        view['comic_num'].text = str(num)
        view['slider'].value = num/latest
        view.comic = None
        objc_util.ObjCInstance(view.navigation_view).navigationController().topViewController().title = objc_util.ns('404 - Not Found')
        return 
    console.show_activity()
    comic = get_info(num)
    if comic:
        if num in faves:
            view['fav'].image = ui.Image('iob:ios7_heart_32')
        else:
            view['fav'].image = ui.Image('iob:ios7_heart_outline_32')
        #view['comic'].image = ui.Image('loading.png')
        view['wv'].load_url(os.path.abspath('loading.png'))
        view.current = num
        view['comic_num'].text = str(num)
        view['slider'].value = num/latest
        view.comic = comic
        
        #view['comic'].image = get_comic(view.comic['img'])
        view['wv'].load_url(get_comic(view.comic['img']))
        objc_util.ObjCInstance(view.navigation_view).navigationController().topViewController().title = objc_util.ns(view.comic['title'])
    
    console.hide_activity()
Exemplo n.º 3
0
    def populate_table(self):
        console.show_activity()
        if callable(self.items):
            items = self.items()
        else:
            items = self.items

        dropdownlist = []
        self.listsource.items = dropdownlist
        self.tbl.reload()
        for item in items:

            def ani():
                dropdownlist.append(item)
                offset = self.tbl.content_offset
                self.listsource.items = dropdownlist
                self.tbl.reload()
                try:
                    self.listsource.selected_row = self.listsource.items.index(
                        self.textfield.text)
                    self.listsource.tableview.selected_row = (
                        0, self.listsource.selected_row)
                except ValueError:
                    #self.listsource.selected_row=-1
                    self.listsource.tableview.selected_row = (0, -1)
                self.tbl.content_offset = tuple(offset)

            ui.animate(ani, 0.1)
        console.hide_activity()
Exemplo n.º 4
0
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()
Exemplo n.º 5
0
 def row_selected(self, ds):
     note = self.notes[ds.selected_row]
     #print note
     console.show_activity('Getting note...')
     note_detail = pb.get_note_details(note.get('id'))
     console.hide_activity()
     note_view = NoteView(note_detail)
Exemplo n.º 6
0
def wordnik(word: str):
    """Return the WordNik definition of a word.

    If can't connect to WordNik API, then return opted() instead.
    """
    try:
        console.show_activity()
        defs = wn_api.getDefinitions(word, limit=5) or []
        suggs = wn_api.getWord(word, includeSuggestions=True)
        console.hide_activity()
        suggestions = suggs.suggestions or []
        definitions = [{
            'text': d.text,
            'partOfSpeech': d.partOfSpeech
        } for d in defs]
        if defs:
            attribution = defs[0].attributionText
            attribution_url = defs[0].attributionUrl
        else:
            attribution = ''
            attribution_url = ''
        data = {
            'definitions': definitions,
            'attribution': attribution,
            'attributionUrl': attribution_url,
            'suggestions': suggestions,
            'messages': []
        }
    except URLError:
        data = opted(word)
        data['messages'].append('''WordRoom couldn't connect to WordNik.com to
                                retrieve online definitions.''')
    return data
Exemplo n.º 7
0
def main():
    console.alert(
        'Shortcut Generator',
        "This script adds a shortcut icon to running the MetreiOS app on your homepage. Your default browser MUST be Safari",
        'Continue')
    # Fetch config json
    root_dir = os.path.abspath(os.path.expanduser('~Documents/' + 'MetreiOS'))
    with open('../metre_ios_install_config.json') as f:
        configs = json.load(f)

    currentversion = configs['git_repo']
    label = 'MetreiOS'
    url = 'pythonista3://MetreiOS' + '/' + currentversion + '/MainMetre.py?action=run'

    img = Image.open(
        BytesIO(
            urllib.request.urlopen(
                "https://drive.google.com/uc?export=view&id=1--lLdK8dHtBOBwsZyFu0g3TRIjhA_0XK"
            ).read()))

    console.show_activity('Preparing Configuration profile...')
    data_buffer = BytesIO()
    img.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)
Exemplo n.º 8
0
 def checkForUpdate(self):
     try:
         console.show_activity('Checking for update...')
         response = requests.get(self.latestReleaseUrl)
         data = json.loads(response.text)
         rel = release(data)
         console.hide_activity()
         if rel.prerelease == False:
             if LooseVersion(self.currentVersion) < LooseVersion(
                     rel.tag_name.replace('v', '')):
                 ret = console.alert(
                     'Update available',
                     rel.tag_name +
                     ' is available, would you like to install it. \n\n Details: '
                     + rel.body.replace('\r\n', '\n'),
                     hide_cancel_button=True,
                     button1='No',
                     button2='Yes')
                 if ret == 2:
                     self.install(rel)
             else:
                 console.alert('No update available',
                               'v' + self.currentVersion +
                               ' is the current version.',
                               hide_cancel_button=True,
                               button1='Ok')
     except requests.exceptions.ConnectionError as e:
         console.alert('Check your internet connection',
                       'Unable to check for update.',
                       hide_cancel_button=True,
                       button1='Ok')
Exemplo n.º 9
0
 def tableview_did_select(self, tableview, section, row):
     u"""Called when the user selects a row.
     """
     if not tableview.editing:
         console.show_activity()
         self.app.push_view(self.app.make_file_list(FileItem(self.entries[row][0])))
         console.hide_activity()
Exemplo n.º 10
0
 def __init__(self):
     console.show_activity('Loading...')
     self.docsetFolder = 'Docsets'
     self.setup()
     self.dbmanager = DBManager.DBManager()
     self.theme_manager = ThemeManager.ThemeManager('Themes')
     self.docset_manager = DocsetManager.DocsetManager(
         'Images/icons', 'Images/types', ServerManager.ServerManager())
     self.cheatsheet_manager = CheatsheetManager.CheatsheetManager(
         ServerManager.ServerManager(), 'Images/icons', 'Images/types')
     self.usercontributed_manager = UserContributedManager.UserContributedManager(
         ServerManager.ServerManager(), 'Images/icons', 'Images/types')
     self.stackoverflow_manager = StackOverflowManager.StackOverflowManager(
         ServerManager.ServerManager(), 'Images/icons', 'Images/types')
     self.webSearchManager = WebSearchManager.WebSearchManager(
         'Images/types')
     self.main_view = self.setup_main_view()
     self.navigation_view = self.setup_navigation_view()
     self.docset_management_view = self.setup_docset_management_view()
     self.cheatsheet_management_view = self.setup_cheatsheetmanagement_view(
     )
     self.usercontributed_management_view = self.setup_usercontributedmanagement_view(
     )
     self.stackoverflow_management_view = self.setup_stackoverflowmanagement_view(
     )
     self.settings_view = self.setup_settings_view()
     self.docsetView = self.setup_docset_view()
     self.docsetIndexView = self.setup_docsetindex_view()
     self.docsetWebView = self.setup_docsetweb_view()
     UISearchControllerWrapper.Theme_manager = self.theme_manager
     console.hide_activity()
Exemplo n.º 11
0
def do_args(arg, quoted_output, output):
  if not quoted_output:
    cmd = '{}://x-callback-url/'.format(arg)
  else:
    if arg == 'onewriter':
      the_path = sys.argv[2]
      the_file = sys.argv[3]
      fmt = '{}://x-callback-url/append?path={}%2F&name={}&type=Local&text={}'
      cmd = fmt.format(arg, the_path, the_file, quoted_output)

    if arg == 'editorial':
      clipboard.set(output)
      '''
      'Append Open Doc' is an Editorial workflow
      available here:
      http://www.editorial-workflows.com/workflow/5278032428269568/g2tYM1p0OZ4
      '''
      cmd = '{}://?command=Append%20Open%20Doc'.format(arg)

    if arg == 'drafts4':
      '''
      Append gps data to open Draft doc using the 2nd
      argument from calling URL as the UUID of the
      open doc
      '''
      fmt = '{}://x-callback-url/append?uuid={}&text={}'
      cmd = fmt.format(arg, sys.argv[2], quoted_output)

  webbrowser.open(cmd)
  console.hide_activity()
  sys.exit('Finished!')
Exemplo n.º 12
0
def main_app_extension() -> int:
    import appex
    import webbrowser
    import console
    result_cmd = None
    console.show_activity()
    last_url = None
    last_title = None
    try:
        url_list = appex.get_urls()
        result_list = []
        for url in url_list:
            last_url = url
            markdown_template, last_title = safari_url(url)
            result_list.append(markdown_template)
        all_docs = "\n---\n".join(result_list)
        docs_url = quote(all_docs, safe='')
        last_url_encoded = quote(last_url, safe='')
        last_title_encoded = quote(last_title, safe='')
        # Open IA Writer to handle the new document
        # result_cmd = f'ia-writer://new?&text={docs_url}&edit=true'
        #result_cmd = f'x-devonthink://clip?text={docs_url}&location={last_url_encoded}&title={last_title_encoded}'
        result_cmd = f'x-devonthink://createMarkdown?text={docs_url}&title={last_title_encoded}&tags=Safari%20Gold'
    finally:
        console.hide_activity()
        appex.finish()
    if result_cmd is not None:
        webbrowser.open(result_cmd)
    return 0
Exemplo n.º 13
0
 def url_to_local_file(in_url, in_file_name):
     short_name = in_file_name.rpartition('/')[2] or in_file_name
     console.show_activity('Downloading: ' + short_name)
     time.sleep(1)
     with open(in_file_name, 'w') as out_file:
         out_file.write(requests.get(in_url).content)
     console.hide_activity()
Exemplo n.º 14
0
 def tableview_did_select(self, tableview, section, row):
     # Called when the user selects a row
     if not tableview.editing:
         fi = self.lists[section][row]
         if section == 0:
             console.show_activity()
             nav.push_view(make_file_list(fi))
             console.hide_activity()
         elif section == 1:
             filetype = fi.fileinfo.filetype
             if fi.fileinfo.file_ext in ("htm", "html"):
                 webbrowser.open("file://" + fi.path)
                 nav.close()
             elif filetype in ("code", "code_tags", "text"):
                 open_path(fi.path)
                 nav.close()
             elif filetype == "audio":
                 spath = rel_to_app(fi.path.rsplit(".", 1)[0])
                 sound.load_effect(spath)
                 sound.play_effect(spath)
             elif filetype == "image":
                 console.show_image(fi.path)
             else:
                 console.quicklook(fi.path)
                 nav.close()
Exemplo n.º 15
0
 def url_to_local_file(in_url, in_file_name):
     short_name = in_file_name.rpartition('/')[2] or in_file_name
     console.show_activity('Downloading: ' + short_name)
     time.sleep(1)
     with open(in_file_name, 'w') as out_file:
         out_file.write(requests.get(in_url).content)
     console.hide_activity()
Exemplo n.º 16
0
def main():
    ### CHANGE THESE VALUES:
    to = console.input_alert('Send Email To', 'Enter an email address below')
    subject = console.input_alert('Subject',
                                  'Enter the subject of the email below')
    gmail_pwd = keychain.get_password('Gmail', '*****@*****.**')
    gmail_user = '******'

    #Load a sample image, modify as needed:
    image = clipboard.get_image()

    print 'Connecting...'
    smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
    console.show_activity()
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(gmail_user, gmail_pwd)

    print 'Preparing message...'
    outer = MIMEMultipart()
    outer['Subject'] = subject
    outer['To'] = to
    outer['From'] = gmail_user
    outer.preamble = 'You will not see this in a MIME-aware email reader.\n'
    attachment = get_attachment(image)
    outer.attach(attachment)
    composed = outer.as_string()

    print 'Sending...'
    smtpserver.sendmail(gmail_user, to, composed)
    smtpserver.close()
    console.hide_activity()
    sound.play_effect('Bleep')
    print 'Done.'
Exemplo n.º 17
0
def load_comic(view, num):
    if num == 404:
        #view['comic'].image = ui.Image('loading.png')
        view['wv'].load_url(os.path.abspath('loading.png'))
        view.current = num
        view['comic_num'].text = str(num)
        view['slider'].value = num / latest
        view.comic = None
        objc_util.ObjCInstance(view.navigation_view).navigationController(
        ).topViewController().title = objc_util.ns('404 - Not Found')
        return
    console.show_activity()
    comic = get_info(num)
    if comic:
        if num in faves:
            view['fav'].image = ui.Image('iob:ios7_heart_32')
        else:
            view['fav'].image = ui.Image('iob:ios7_heart_outline_32')
        #view['comic'].image = ui.Image('loading.png')
        view['wv'].load_url(os.path.abspath('loading.png'))
        view.current = num
        view['comic_num'].text = str(num)
        view['slider'].value = num / latest
        view.comic = comic

        #view['comic'].image = get_comic(view.comic['img'])
        view['wv'].load_url(get_comic(view.comic['img']))
        objc_util.ObjCInstance(view.navigation_view).navigationController(
        ).topViewController().title = objc_util.ns(view.comic['title'])

    console.hide_activity()
Exemplo n.º 18
0
 def reinstallCurrentVersion(self):
     if not os.path.exists('.version'):
         console.alert('Install error',
                       'Unable to determine current version.',
                       hide_cancel_button=True,
                       button1='Ok')
     else:
         console.show_activity('Checking for v' + self.currentVersion +
                               ' install files...')
         releases = self.getAllReleases(getAll=True)
         try:
             console.hide_activity()
             release = releases[self.currentVersion]
             self.install(release)
         except KeyError as e:
             console.hide_activity()
             res = console.alert(
                 'Install error',
                 'Unable to find v' + self.currentVersion +
                 ' install files. Would you like to install the latest version?',
                 hide_cancel_button=True,
                 button1='No',
                 button2='Yes')
             if res == 2:
                 self.checkForUpdate()
Exemplo n.º 19
0
    def install(self, release):
        console.show_activity('Installing ' + release.tag_name)
        request = requests.get(release.zipball_url)
        file = zipfile.ZipFile(BytesIO(request.content))
        toRemove = file.namelist()[0]

        filelist = [
            f for f in os.listdir('.') if not f in [
                'Docsets', '.wcsync', '.themesConfig', '.migrations.db',
                '.settings'
            ]
        ]
        for f in filelist:
            if os.path.isdir(f):
                shutil.rmtree(f)
            else:
                os.remove(f)
        file.extractall()
        for filename in os.listdir(toRemove):
            shutil.move(os.path.join(toRemove, filename), filename)
        shutil.rmtree(toRemove)
        file.close()

        f = open('.version', 'w')
        f.write(release.tag_name.replace('v', ''))
        f.close()
        console.hide_activity()
        console.alert('Installed',
                      release.tag_name +
                      ' installed, please restart Pythonista',
                      hide_cancel_button=True,
                      button1='Ok')
Exemplo n.º 20
0
def get_location_ios():
    try:
        console.show_activity()
        location.start_updates()
        coordinates = location.get_location()
        location.stop_updates()
        console.hide_activity()
        results = location.reverse_geocode(coordinates)

        if not results:
            results = [{'City': 'N/A', 'Country': 'N/A'}]

        dms_lat, dms_lng = dd2dms(coordinates['latitude'],
                                  coordinates['longitude'])

        return SimpleNamespace(**{
            'latitude': coordinates['latitude'],
            'longitude': coordinates['longitude'],
            'city': results[0]['City'],
            'country': results[0]['Country'],
            'altitude': float(coordinates['altitude']),
            'dms_latitude': dms_lat,
            'dms_longitude': dms_lng,
        })
    except Exception as e:
        print(e.with_traceback)
        print('Não foi possível obter a localização atual.'
              '\nA utilizar predefinição...\n')
        console.hide_activity()
        return None
Exemplo n.º 21
0
 def tableview_did_select(self, tableview, section, row):
     # Called when the user selects a row
     if not tableview.editing:
         fi = self.lists[section][row]
         if section == 0:
             console.show_activity()
             nav.push_view(make_file_list(fi))
             console.hide_activity()
         elif section == 1:
             filetype = fi.fileinfo.filetype
             if fi.fileinfo.file_ext in ("htm", "html"):
                 webbrowser.open("file://" + fi.path)
                 nav.close()
             elif filetype in ("code", "code_tags", "text"):
                 open_path(fi.path)
                 nav.close()
             elif filetype == "audio":
                 spath = rel_to_app(fi.path.rsplit(".", 1)[0])
                 sound.load_effect(spath)
                 sound.play_effect(spath)
             elif filetype == "image":
                 console.show_image(fi.path)
             else:
                 console.quicklook(fi.path)
                 nav.close()
Exemplo n.º 22
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)
Exemplo n.º 23
0
def exporti(sender):
	console.show_activity()
	ishare['colorbox'].end_editing()
	
	color = ishare['colorbox'].text
	
	if color != '':
		if not color.startswith('#'):
			color = '#'+color
		if len(color) != 7:
			raise ValueError('Must be hexidecimal')
		im = RenderASCII(out, bgcolor=color)
		i.image = pil_to_ui(im)
		rootView.background_color = color
		view2.draw()
		
		
	else:
		im = outim
	
	
	b = BytesIO()
	im.save(b, 'PNG')
	img_data = b.getvalue()
	
	console.hide_activity()
	
	_dialogs.share_image_data(img_data)
Exemplo n.º 24
0
def main(im):
    # Create the ASCII
    global out
    console.show_activity("Processing...")
    out = image2ASCII(im)
    console.hide_activity()
    # Render onto an image
    global outim
    console.show_activity("Rendering...")
    outim = RenderASCII(out)
    console.hide_activity()

    rootView.background_color = 0.92

    global i
    i = ui.ImageView()

    i.frame = (0, 10, 1024, 768)
    i.content_mode = ui.CONTENT_SCALE_ASPECT_FIT

    i.image = pil_to_ui(outim)
    rootView.add_subview(i)

    close.bring_to_front()

    view2.remove_subview(ishare)
    view2.x = 247
    view2.y = -285
    rootView.add_subview(view2)

    time.sleep(1.5)
    ui.animate(pulldown, 1)
Exemplo n.º 25
0
    def scan(self):
        self.result = []
        _gate_way = '.'.join(self.current_ip.split('.')[:3])
        # gate_way = _gate_way+'.1'  # pyflakes says this is not used
        if self.alert:
            console.show_activity('Scanning.....')
        for x in range(1, 256):
            ip = '{}.{}'.format(_gate_way, x)
            self.thread_limit.acquire()
            threading.Thread(target=self.pscan,
                             args=(ip, self.port),
                             name='PortScanner').start()

        thread_list = [
            x for x in threading.enumerate() if x.name == 'PortScanner'
        ]
        for _ in thread_list:
            _.join()
        if self.alert:
            if self.result:
                console.hud_alert(' '.join(self.result), 'success', 1)
            else:
                console.hud_alert('Not found', 'error', 1)
            console.hide_activity()
        return self.result
Exemplo n.º 26
0
Arquivo: gh.py Projeto: zychen/stash
def gh_create(args):
    '''Usage: gh create [options] <name> 

	Options:
	-h, --help             This message
	-s <desc>, --description <desc>		Repo description
	-h <url>, --homepage <url>				Homepage url
	-p, --private          private
	-i, --has_issues       has issues
	-w, --has_wiki  			 has wiki
	-d, --has_downloads    has downloads
	-a, --auto_init     		create readme and first commit
	-g <ign>, --gitignore_template <ign>  create gitignore using string
	
	
	'''
    kwargs = {
        key[2:]: value
        for key, value in args.items() if key.startswith('--') and value
    }
    console.show_activity()
    try:
        g, user = setup_gh()
        r = user.create_repo(args['<name>'], **kwargs)
        print('Created %s' % r.html_url)
    finally:
        console.hide_activity()
Exemplo n.º 27
0
def start_gui(check_wakeup):
    global logger

    console.show_activity("Scanning repositories...")
    if check_wakeup:
        logger.info("Checking if wakeup is required...")

    sync_tools = []
    configs = sync.find_sync_configs()
    working_copy_configs = []
    working_copy_configs.extend(filter(lambda config: config.repository.working_copy_wakeup, configs))
    working_copy_active = ENABLE_WORKING_COPY_SUPPORT and len(working_copy_configs) > 0

    if working_copy_active and check_wakeup:
        wakeup_webdav_server(working_copy_configs[0])
        logger.info("Exiting to await callback from Working Copy...")
        console.hide_activity()
        return

    logger.info("Starting GUI...")

    for config in configs:
        logger.info("Found configuration '%s'..." % config.repository.name)

        try:
            sync_tool = sync.SyncTool(config)
            sync_tools.append(sync_tool)

        except Exception as e:
            logger.exception("Error '%s' while processing configuration '%s'" % (str(e), config.repository.name))

    selector = sync_selector.SyncSelector()
    console.hide_activity()
    selector.select(sync_tools, working_copy_active=working_copy_active)
Exemplo n.º 28
0
 def tableview_did_select(self, tableview, section, row):
     u"""Called when the user selects a row.
     """
     if not tableview.editing:
         fi = self.lists[section][row]
         if section == 0:
             console.show_activity()
             self.app.push_view(self.app.make_file_list(fi))
             console.hide_activity()
         elif section == 1:
             group = fi.constants.group
             if fi.constants.ext in (u"htm", u"html"):
                 webbrowser.open(u"file://" + fi.path)
                 self.app.close()
             elif group in ("code", "code_tags", "text"):
                 open_path(fi.path)
                 self.app.close()
             elif group == "audio":
                 spath = rel_to_app(fi.path.rsplit(u".", 1)[0])
                 sound.load_effect(spath)
                 sound.play_effect(spath)
             elif group == "image":
                 console.show_image(fi.path)
             else:
                 self.app.close()
                 time.sleep(ANIM_DELAY)
                 console.quicklook(fi.path)
Exemplo n.º 29
0
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()
Exemplo n.º 30
0
 def tableview_did_select(self, tableview, section, row):
     u"""Called when the user selects a row.
     """
     if not tableview.editing:
         fi = self.lists[section][row]
         if section == 0:
             console.show_activity("Loading file list...")
             self.app.push_view(self.app.make_file_list(fi))
             console.hide_activity()
         elif section == 1:
             group = fi.constants.group
             if fi.constants.ext in (u"htm", u"html"):
                 webbrowser.open(u"file://" + fi.path)
                 self.app.close()
             elif group in ("code", "code_tags", "text"):
                 open_path(fi.path)
                 self.app.close()
             elif group == "audio":
                 spath = rel_to_app(fi.path.rsplit(u".", 1)[0])
                 sound.load_effect(spath)
                 sound.play_effect(spath)
             elif group == "image":
                 console.show_image(fi.path)
             else:
                 self.app.close()
                 time.sleep(ANIM_DELAY)
                 console.quicklook(fi.path)
Exemplo n.º 31
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)
Exemplo n.º 32
0
 def webview_did_finish_load(webview):
     # Get page title with some JavaScript
     currenturl = webview.eval_js('window.location.href')
     webview.name = webview.eval_js('document.title').split(' -')[0]
     console.hide_activity()
     if url and not wiki.back:
         wiki.history.append(url)
         wiki.histIndex += 1
Exemplo n.º 33
0
 def tableview_did_select(self, tableview, section, row):
     u"""Called when the user selects a row.
     """
     if not tableview.editing:
         console.show_activity("Loading file list...")
         self.app.push_view(
             self.app.make_file_list(FileItem(self.entries[row][0])))
         console.hide_activity()
def backup_youtubedl(sender):
    console.show_activity('Checking for youtube-dl')
    if os.path.isdir(youtubedl_location+youtubedl_dir):
        console.show_activity('Backing up youtube-dl')
        if not os.path.exists(backup_location):
            os.makedirs(backup_location)
        shutil.move(youtubedl_location+youtubedl_dir,backup_location+youtubedl_dir+ time.strftime('%Y%m%d%H%M%S'))
    console.hide_activity()
Exemplo n.º 35
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()
Exemplo n.º 36
0
def backup_youtubedl(sender):
    console.show_activity('Checking for youtube-dl')
    if os.path.isdir(youtubedl_location+youtubedl_dir):
        console.show_activity('Backing up youtube-dl')
        if not os.path.exists(backup_location):
            os.makedirs(backup_location)
        shutil.move(youtubedl_location+youtubedl_dir,backup_location+youtubedl_dir+ time.strftime('%Y%m%d%H%M%S'))
    console.hide_activity()
Exemplo n.º 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()
Exemplo n.º 38
0
Arquivo: gh.py Projeto: zychen/stash
def gh_pull(args):
    '''Usage: 
	gh pull <reponame> <base> [<head>]
	gh pull <reponame> <base> [<head>] --title <title> [--body <body>]
	gh pull <reponame> <base> [<head>] -i <issue>

Options:
	-h, --help   							This message
	-t <title>, --title <title>  	Title of pull request
	-b <body>, --body <body>  		Body of pull request [default: ]
	-i <issue>, --issue <issue>  	Issue number
Examples:
	gh pull stash ywangd jsbain 
	gh pull stash ywangd:dev jsbain:dev
	gh pull stash :dev :master
			
	base and head should be in the format owner:branch.
	if base owner is omitted, owner of parent repo is used.
	if head owner is omitted, user is used
	'''

    console.show_activity()
    try:
        g, user = setup_gh()
        reponame = args['<reponame>']
        baseowner, basebranch = parse_branch(args['<base>'])
        if not baseowner:
            baseowner = parent_owner(reponame)
        if not args['<head>']:
            args['<head>'] = ':'
        headowner, headbranch = parse_branch(args['<head>'])
        if not headowner:
            headowner = user.login

        baserepo = g.get_user(baseowner).get_repo(reponame)

        kwargs = {}
        if args['--issue']:
            kwargs['issue'] = baserepo.get_issue(args['--issue'])
        elif not args['--title']:
            kwargs['title'] = input('Enter pull title:')
            kwargs['body'] = input('Enter pull body:')
        else:
            kwargs['title'] = args['--title']
            kwargs['body'] = args['--body'] or ''

        kwargs['base'] = basebranch
        kwargs['head'] = ':'.join([headowner, headbranch])
        pullreq = baserepo.create_pull(**kwargs)

        print('Created pull %s' % pullreq.html_url)
        print('Commits:')
        print([(x.sha, x.commit.message) for x in pullreq.get_commits()])
        print('Changed Files:')
        print([x.filename for x in pullreq.get_files()])
    finally:
        console.hide_activity()
    print('success')
Exemplo n.º 39
0
		def func_wrapper(*args, **kwargs):
			console.show_activity(msg)
			try:
				result = func(*args, **kwargs)
				console.hide_activity()
				return result
			except Exception:
				console.hide_activity()
				raise
Exemplo n.º 40
0
def main(args):
    ap = argparse.ArgumentParser()
    ap.add_argument('-o',
                    '--output-file',
                    nargs='?',
                    help='save content as file')
    ap.add_argument('url',
                    nargs='?',
                    help='the url to read from (default to clipboard)')

    ns = ap.parse_args(args)
    url = ns.url or clipboard.get()
    output_file = ns.output_file or url.split('/')[-1]

    console.show_activity()
    try:

        print('Opening: %s\n' % url)
        u = urlopen(url)

        meta = u.info()
        try:
            if _stash.PY3:
                file_size = int(meta["Content-Length"])
            else:
                file_size = int(meta.getheaders("Content-Length")[0])
        except (IndexError, ValueError, TypeError):
            file_size = 0

        print("Save as: {} ".format(output_file), end="")
        print("({} bytes)".format(file_size if file_size else "???"))

        with open(output_file, 'wb') as f:
            file_size_dl = 0
            block_sz = 8192
            while True:
                buf = u.read(block_sz)
                if not buf:
                    break
                file_size_dl += len(buf)
                f.write(buf)
                if file_size:
                    status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl *
                                                   100. / file_size)
                else:
                    status = "%10d" % file_size_dl
                print('\r' + status, end="")
            print("")

    except Exception:
        print('invalid url: %s' % url)
        sys.exit(1)

    finally:
        console.hide_activity()

    sys.exit(0)
Exemplo n.º 41
0
 def network(self):
     if config.ios:
         if self.network:
             console.hide_activity()
             self.network = False
         else:
             console.show_activity()
             self.network = True
     else:
         pass
Exemplo n.º 42
0
 def _wrap_run(self):
     try:
         self._real_run()
     except Exception as e:
         console.hide_activity()
         console.alert('Error occured',
                       str(e) +
                       '\n\n Please close application and start again',
                       'Ok',
                       hide_cancel_button=True)
Exemplo n.º 43
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')
Exemplo n.º 44
0
def get_tweets(sender):
	tlist = []
	tweets = twitter.get_home_timeline(account)
	console.show_activity('Refreshing')
	time.sleep(1)
	for t in tweets:
		tlist.append(t.get('text'))
	timeline.data_source = ui.ListDataSource(items=tlist)
	timeline.reload()
	console.hide_activity()
Exemplo n.º 45
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'
Exemplo n.º 46
0
def main(args):
    ap = argparse.ArgumentParser()
    ap.add_argument('-o',
                    '--output-file',
                    nargs='?',
                    help='save content as file')
    ap.add_argument('url',
                    nargs='?',
                    help='the url to read from (default to clipboard)')

    ns = ap.parse_args(args)
    url = ns.url or clipboard.get()
    output_file = ns.output_file or url.split('/')[-1]

    console.show_activity()
    try:

        print 'Opening: %s' % url
        u = urllib2.urlopen(url)

        meta = u.info()
        try:
            file_size = int(meta.getheaders("Content-Length")[0])
        except IndexError:
            file_size = 0

        print "Save as: %s " % output_file,
        print "(%s bytes)" % file_size if file_size else ""

        with open(output_file, 'wb') as f:
            file_size_dl = 0
            block_sz = 8192
            while True:
                buf = u.read(block_sz)
                if not buf:
                    break
                file_size_dl += len(buf)
                f.write(buf)
                if file_size:
                    status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl *
                                                   100. / file_size)
                else:
                    status = "%10d" % file_size_dl
                print '\r' + status,
            print

    except:
        print 'invalid url: %s' % url
        sys.exit(1)

    finally:
        console.hide_activity()

    sys.exit(0)
Exemplo n.º 47
0
 def push_callback(user,pw):
     print  "Attempting to push to: {0}, branch: {1}".format(remote, branch_name)
     console.show_activity()
     if user:
         opener = auth_urllib2_opener(None, remote, user, pw)
         porcelain.push(repo.path, remote, branch_name, opener=opener)
         keychain.set_password(keychainservice, user, pw)
     else:
         porcelain.push(repo.repo, result.url, branch_name)
     console.hide_activity()
     console.hud_alert('push complete')
Exemplo n.º 48
0
    def settings_action(self, sender):
        Dialog_List =[{'type':'text','title':'RSS Feed 1','key':'feeds', 'value': config.feeds},
        #{'type':'text','title':'RSS Feed 2','key':'feed2', 'value': config.feed_2},
{'type': 'switch', 'title': 'Twitter Feed', 'key':'twitter', 'value': config.twitter_mode},]
        settings = dialogs.form_dialog(title='Settings', fields=Dialog_List)
        console.show_activity()
        #if settings is None:
          #print 'Cancelled'
        #else:
          #self.updatepy(settings['feed1'], settings['feed2'], settings['twitter'])
        self.update_news()
        console.hide_activity()
Exemplo n.º 49
0
	def refresh_remote_list(self):
		
		try:
			attr = self.sftp.listdir_attr(self.remotePath)
		except Exception as e:
			console.hide_activity()
			console.hud_alert(str(e), 'error')
			return 
			
		self.remote_dict = {}
		files = []
		
		if self.remotePath == '/':
			dirs  = []
		else:
			dirs  = ['..']
			full_path = '/'.join(self.remotePath.split('/')[:-1])
			if full_path == '':
				full_path = '/'
			self.remote_dict['..'] = {'full_path':full_path, 'type':'dir'}

		
		for entry in attr:
			size = entry.st_size
			longname = entry.longname
			mtime = entry.st_mtime #最終変更時刻
			atime = entry.st_atime #最終アクセス時刻
			mtime = datetime.fromtimestamp(mtime)
			atime = datetime.fromtimestamp(atime)
			longname = longname
			type = 'Unknown'
			path = str(entry)[55:]
			full_path = os.path.join(self.remotePath, path)
			
			if str(entry)[0] ==  'd':	
				type = 'dir'
				dirs.append(path)
			elif str(entry)[0] ==  '-':
				type = 'file'
				files.append(path)
			elif str(entry)[0] ==  'l':
				type = 'link'
				files.append(path)
				
			remote_dict = {'full_path':full_path, 'size':size, 'longname':longname, 'type':type, 'atime':atime, 'mtime':mtime}
			self.remote_dict[path] = remote_dict
			
		all = sorted(dirs)
		for file in sorted(files):
			all.append(file)
		self.remote_list = all
		self.view['lb_remote'].text = self.remotePath
		self.refresh_table(self.tv_remote)
Exemplo n.º 50
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:
        print "User canceled the input."
Exemplo n.º 51
0
def main():
    song_page = None
    if (len(sys.argv) > 0):
        try:
            song_page = sys.argv[1]
        except Exception:
            song_page = None
    if not song_page:
        print repr(sys.argv)
        return
    console.clear()
    
    # kopiert den Namen der Datei in die zwischenablage
    console.show_activity()
    soup = bs4.BeautifulSoup(urllib.urlopen(song_page))
    pageTitle = soup.title.string
    console.hide_activity()
    console.clear()
    clipboard.set(pageTitle)
    print pageTitle
    
    
    print "Grabbing:", song_page
    sess = requests.Session()
    sess.headers.update({'User-Agent': 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5'})
    print " .. getting xtsite and js .. "
    find_xtsite_js = sess.get(song_page).text
    xtsite = find_xtsite_js.rsplit('xtsite',1)[1].split(';',1)[0].split('"',1)[1].split('"',1)[0]
    the_js = find_xtsite_js.rsplit('m-a.sndcdn.com',1)[1].split('"',1)[0].split('/')[-1]
    print " .. getting client_id .. "
    new_headers = {'Accept-Encoding': 'identity', 'Connection': 'close'}
    sess.headers.update(new_headers)
    find_client_id = sess.get('http://m-a.sndcdn.com/' + the_js)
    client_id = find_client_id.content[:250].split('clientId',1)[1].split(';',1)[0].split('"',1)[1].split('"',1)[0]
    print "id:", client_id
    today = datetime.datetime.utcnow().now()
    # ---- cookies here ----
    xtant='1'
    xtan='-'
    xtvrn='$'+xtsite+'$'
    xtidc = today.strftime('%y') + ('%02d' % (today.month-1)) + today.strftime('%d%H%M%S') + str(random.randint(10000,999999))
    sc_anonymous_id = '-'.join([str(random.randint(10000,999999)) for x in range(4)])
    # ---- end cookies ----
    sess.headers.update({'X-Requested-With': 'XMLHttpRequest'})
    new_cookies = {'xtant': xtant, 'xtan': xtan, 'xtvrn': xtvrn, 'xtidc': xtidc, 'sc_anonymous_id': sc_anonymous_id}
    print " .. getting track id .. "
    find_track_id = sess.get('http://m.soundcloud.com/_api/resolve?url=%s&client_id=%s&format=json' % (song_page, client_id), cookies = new_cookies, allow_redirects=False).headers['location']
    track_id = find_track_id.split('.json',1)[0].rsplit('/',1)[-1]
    print "id:", track_id
    mp3_url = 'http://api.soundcloud.com/tracks/%s/stream?client_id=%s' % (track_id, client_id)
    download_url = mp3_url.replace('http://', 'ghttp://')
    webbrowser.open(download_url)
Exemplo n.º 52
0
def main():
    song_page = None
    if (len(sys.argv) > 0):
        try:
            song_page = sys.argv[1]
        except Exception:
            song_page = None
    if not song_page:
        print(repr(sys.argv))
        return
    console.clear()
    
    # kopiert den Namen der Datei in die zwischenablage
    console.show_activity()
    soup = bs4.BeautifulSoup(urllib.urlopen(song_page))
    pageTitle = soup.title.string
    console.hide_activity()
    console.clear()
    clipboard.set(pageTitle)
    print("Dateiname: " 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://', 'rhttp://')
    webbrowser.open(download_url)
Exemplo n.º 53
0
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"
Exemplo n.º 54
0
    def tableview_did_select(self, tableview, section, row): 
        console.show_activity()
        feed = feedparser.parse(self.feeds[row]['url'])
        
        rss_controller = RSSController(feed)

        tv = ui.TableView()
        tv.name = self.feeds[row]['title']
        tv.allows_multiple_selection_during_editing = True
        tv.data_source = rss_controller
        tv.delegate = rss_controller

        table_view.navigation_view.push_view(tv)
        console.hide_activity()
Exemplo n.º 55
0
 def search(self, sch, ret=False):
     # Remove extra characters
     sch = sch.strip().strip(',').strip('.')
     self.previousSearch = sch
     console.show_activity('Searching...')
     url = self.searchurl + sch
     req = requests.get(url)
     req.raise_for_status()
     console.hide_activity()
     # Show search results in table view unless the search redirects
     # to a wiki page
     if req.url.startswith(self.searchurl):
         return False if ret else self.showResults(url)
     else:
         return req.url if ret else self.loadPage(req.url)
Exemplo n.º 56
0
def calc_fingerings(currentState):
	try:
		key = currentState['root']['noteValue']
		note = currentState['root']['title']  # since "C" has a note value of zero, use note title as indicator
	except:
		return
	try:
		chordtype = currentState['chord']['fingering']
	except:
		return
	try:
		tuning = currentState['instrument']['notes']
	except:
		return
	try:
		instrument = currentState['instrument']
	except:
		return
	try:
		filters = currentState['filters']
	except:
		return
	span = currentState['instrument']['span']
	option = 0
	
	if note and chordtype and tuning:
		fingerPositions = []	
		fingerings = []
		console.show_activity()
		for position in range(0,12,span):
			fingerings = fingerings + findFingerings(key, chordtype, tuning, position, span, option)
			#if no fingerings return, abandon the root, then 5th then 3rd.
			if fingerings:
				for fingering in fingerings:
					fingerMarker = fretboard.fingeringDrawPositions(key,chordtype,tuning,fingering)
					fingerPositions.append(fingerMarker)
		result = []
		for fingering,drawposition in zip(fingerings,fingerPositions):
			chordTones = []
			for entry in drawposition:
				chordTones.append(entry[2])
			result.append((drawposition,chordTones,fingering))
		console.hide_activity()
		if filters:
			return apply_filters(filters, result)
		else:
			return result
Exemplo n.º 57
0
def download_tapped(sender):
	'@type sender: ui.Button'
	
	console.clear()

	urlfield = sender.superview['urlfield']
	filenamefield = sender.superview['filenamefield']
	extensionfield = sender.superview['extensionfield']
	extensioncontrol = sender.superview['extensioncontrol']

	if extensioncontrol.selected_index == 0:
		extension = '.py'
	elif extensioncontrol.selected_index == 1:
		extension = '.pyui'
	elif extensioncontrol.selected_index == 2:
		if extensionfield.text != '':
			if not '.' in extensionfield.text:
				extension = '.' + extensionfield.text
			else:
				extension = extensionfield.text
		else:
			extension = ''

	filename = filenamefield.text + extension
	filenum = 1
	while os.path.isfile(filename) is True:
		filename = filenamefield.text + ' ({})'.format(str(filenum)) + extension
		filenum += 1
	hud_alert('Downloading...')
	try:
		console.show_activity()
		url = urllib2.urlopen(urlfield.text).read()
	except (ValueError, urllib2.URLError):
		hud_alert('URL not valid', icon = 'error')
		sys.exit()
	hud_alert("Saving...")
	try:
		with open(filename, "w") as out_file:
			out_file.write(url)
			out_file.close()
	except IOError:
		os.makedirs(os.path.dirname(filename))
		with open(filename, "w") as out_file:
			out_file.write(url)
			out_file.close()
	console.hide_activity()
	hud_alert("Saved!")
Exemplo n.º 58
0
def gitdownload(button):
    index    = view["sgcontrol"].selected_index
    username = view["username"].text = view["username"].text.strip()
    reponame = view["reponame"].text = view["reponame"].text.strip()
    unzip    = view["dounzip"].value
    if not username:
        return error_alert("Please enter username")
    if not reponame:
        return error_alert("Please enter repo name")
    console.show_activity()
    if index == 0:
        download_repo(username, reponame, unzip)
    elif index == 1:
        download_release(username, reponame, unzip)
    elif index == 2:
        download_gist(username, reponame)
    console.hide_activity()
Exemplo n.º 59
0
  def present(self, reference_text, working_text, style='sheet'):
    console.show_activity('Aufbereiten der Graphik')
    self.prepare_histogram_image_view(reference_text, PLOT1_FILENAME)
    self.imageview_plot1.image = ui.Image.named(PLOT1_FILENAME).with_rendering_mode(ui.RENDERING_MODE_ORIGINAL)
    
    self.prepare_histogram_image_view(working_text, PLOT2_FILENAME)
    self.imageview_plot2.image = ui.Image.named(PLOT2_FILENAME).with_rendering_mode(ui.RENDERING_MODE_ORIGINAL)    

    if self.prepare_bar_plot_image_view(reference_text, working_text, PLOT3_FILENAME, self.imageview_plot3.width, self.imageview_plot3.height):
      self.imageview_plot3.image = ui.Image.named(PLOT3_FILENAME).with_rendering_mode(ui.RENDERING_MODE_ORIGINAL)   
      self.imageview_plot3.hidden = False

    else:
      self.imageview_plot3.hidden = True  
    
    console.hide_activity()
    super(StatisticsViewController, self).present(style)
Exemplo n.º 60
0
 def stop_populating(self,sender):
     console.hide_activity()
     root=self.find_root()
     self._abort=True
     if not isinstance(sender,ui.Button):
         #take no action
         self.textfield.text=sender.items[ sender.selected_row]
         def act():
             if self.textfield.action:
                 self.textfield.action(self.textfield)
         ui.delay(act,0.1)
     
     def ani():
         self.dialog.height=0
     def cleanup():
         root.remove_subview(root['overlay'])
     ui.delay(cleanup,0.2)
     ui.animate(ani,0.15)