TheMetaphysicalCrook
TheMetaphysicalCrook
Reputation Top 1%
TheMetaphysicalCrook Crook Accounts
13 Snippets  (61st place)
Published
0 Channels
Created
2 Channels
Following
348 points  (87th place)
Reputation
Top 10% Publisher
Junior Code Generator
Junior Popular Coder
Serious Popular Coder
Senior Popular Coder
Junior Autobiographer
Senior Autobiographer
Master Autobiographer
Junior Snip2Coder
Junior Famous Coder

Recent Snippets See all snippets by TheMetaphysicalCrook

public by TheMetaphysicalCrook  267  0  3  0

Opens the source code from the current page on Textastic

Opens the source code from the current page on Textastic: sourceCodeTextastic.js
javascript:location.href=(function(){var href=location.href;return "textastic"+href.substring(href.indexOf("://"));})();

;

public by moyashi  354  1  3  0

dropboxlogin

dropboxlogin: dropboxloginv2.py
#!python3
# YOU NEED TO INSERT YOUR APP KEY AND SECRET BELOW!
# Go to dropbox.com/developers/apps to create an app.

from __future__ import absolute_import
from __future__ import print_function
app_key = 'YOUR_APP_KEY'
app_secret = 'YOUR_APP_SECRET'

import webbrowser
import dropbox
import keychain

def get_access_token():
	access_token = keychain.get_password('dropboxv2', app_key)
	if access_token:
		return access_token
	auth_flow = dropbox.DropboxOAuth2FlowNoRedirect(app_key, app_secret)
	authorize_url = auth_flow.start()
	print("1. Go to: " + authorize_url)
	print("2. Click \"Allow\" (you might have to log in first).")
	print("3. Copy the authorization code.")
	webbrowser.open(authorize_url, modal=True)
	auth_code = input("Enter the authorization code here: ").strip()
	try:
	    access_token, user_id = auth_flow.finish(auth_code)
	except Exception as e:
	    print('Error: %s' % (e,))
	    return
	keychain.set_password('dropboxv2', app_key, access_token)
	return access_token

def get_client():
	access_token = get_access_token()
	dbx = dropbox.Dropbox(access_token)
	return dbx

def main():
	# Demo if started run as a script...
	# Just print the account info to verify that the authentication worked:
	print('Getting account info...')
	dropbox_client = get_client()
	account_info = dropbox_client.users_get_current_account()
	print('linked account:', account_info)

if __name__ == '__main__':
    main()


;

public by codemonkey85  389  1  3  0

Access Trello data from python / Pythonista

Access Trello data from python / Pythonista: Trello-Pythonista.py
# coding: utf-8

# Note to self: do proper authorization at: https://github.com/sarumont/py-trello/blob/master/trello/util.py

import sys
if sys.argv == [] or len(sys.argv) == 1:
    sys.exit()

clArgs = sys.argv[1].split(',')

if clArgs == [] or len(clArgs) != 4:
    sys.exit()

# Must pass in Trello API Key, Trello App Token, Trello boardId, and Trello username
appKey = clArgs[0]
appToken = clArgs[1]
boardId = clArgs[2]
userName = clArgs[3]

import platform

if platform.system() == 'Darwin':
    if platform.machine().startswith('iP'):
        # we're running on an iOS device
        import console
        import clipboard
        import webbrowser

import urllib2
import urllib
import json

# to properly encode unicode characters in JSON objects
def encode_obj(in_obj):
    def encode_list(in_list):
        out_list = []
        for el in in_list:
            out_list.append(encode_obj(el))
        return out_list
    def encode_dict(in_dict):
        out_dict = {}
        for k, v in in_dict.iteritems():
            out_dict[k] = encode_obj(v)
        return out_dict
    if isinstance(in_obj, unicode):
        return in_obj.encode('utf-8')
    elif isinstance(in_obj, list):
        return encode_list(in_obj)
    elif isinstance(in_obj, tuple):
        return tuple(encode_list(in_obj))
    elif isinstance(in_obj, dict):
        return encode_dict(in_obj)
	return in_obj

myCards = []

args = {
'fields': 'id',
'key': appKey,
'token': appToken
}

memberUrl = "https://api.trello.com/1/members/%s?%s" % (userName, urllib.urlencode((args)))

try:
    data = urllib2.urlopen(memberUrl)
except urllib2.HTTPError as inst:
    raise Exception("Key or Token incorrect")

member = json.loads(data.read())

args = {
'fields': 'id,name,cards',
'key': appKey,
'token': appToken,
'filter': 'open'
}

listsUrl = "https://api.trello.com/1/boards/%s/lists?%s" % (boardId, urllib.urlencode((args)))

try:
    data = urllib2.urlopen(listsUrl)
except urllib2.HTTPError as inst:
    raise Exception("Key or Token incorrect")

lists = json.loads(data.read())

args = {
'fields': 'all',
'key': appKey,
'token': appToken
}

# in case there are lists on the Trello board you don't care about - skipping lists can speed up parsing operations
listsToExclude = []

gen = (x for x in lists if x['name'] not in listsToExclude)
for li in gen:
    cardsUrl = "https://api.trello.com/1/lists/%s/cards?%s" % (li['id'], urllib.urlencode((args)))

    try:
        cardsData = urllib2.urlopen(cardsUrl)
    except urllib2.HTTPError as inst:
        raise Exception("Key or Token incorrect")

    cards = json.loads(cardsData.read())

    gen = (x for x in cards if member['id'] in x['idMembers'])

    for card in gen:
        myCards.append(card)

newline = '\n'
comma = ','
spaceHashtag = ' #'
spaceAtSign = ' @'
myTasks = []
myJsonTasks = []

for card in myCards:
    cardNum = card['idShort']
    cardName = card['name']
    cardLabels = card['labels']
    listId = card['idList']

    listGen = (x for x in lists if x['id'] == listId)
    listName = ''
    for li in listGen:
        listName = li['name']

    taskTitle = "Card #%s - %s" % (cardNum, cardName)

    labelNames = []
    labelNamesNoSpaces = []
    for label in cardLabels:
        labelName = label['name']
        labelNames.append(labelName)
        labelNamesNoSpaces.append(labelName.replace(" ","_"))

    hashtaglabels = spaceHashtag.join(labelNamesNoSpaces)
    atsignlabels = spaceAtSign.join(labelNamesNoSpaces)

    if hashtaglabels != "":
     # for Wunderlist
     hashtaglabels = '#' + hashtaglabels
     # for Todoist
    if atsignlabels != "":
     atsignlabels = '@' + atsignlabels

    taskData = {
    'Title': taskTitle,
    'shortUrl': card['shortUrl'],
    'desc': card['desc'],
    'idShort': cardNum,
    'labels': cardLabels,
    'pos': card['pos'],
    'name': cardName,
    'labelString': comma.join(labelNames),
    'labelStringHashtag': hashtaglabels,
    'labelStringAtSign': atsignlabels,
    'closed': card['closed'],
    'dateLastActivity': card['dateLastActivity'],
    'due': card['due'],
    'idList': listId,
    'ListName': listName,
    'subscribed': card['subscribed'],
    'url': card['url'],
    'FullData': card
    }

# Fields I've left out:
#   badges
#   checkItemStates
#   descData
#   idAttachmentCover
#   idBoard
#   idChecklists
#   idLabels
#   idMembers
#   idMembersVoted
#   manualCoverAttachment
#   shortLink
#   email

    myTasks.append(taskData)
    myJsonTasks.append(urllib.urlencode(taskData).replace('+','%20'))

if platform.system() == 'Darwin':
    if platform.machine().startswith('iP'):
        clipboard.set(newline.join(myJsonTasks))
        webbrowser.open('workflow://')
else:
    # this is for me to dump the data into C#
    jsonTasks = json.dumps(myTasks)
    print jsonTasks


;

public by TheMetaphysicalCrook  311  0  3  0

New from Gist

New from Gist: New from Gist.py
### Based on: https://gist.github.com/b0644f5ed1d94bd32805
### This version strips unicode characters from the downloaded script
### to work around the currently limited unicode support of the editor
### module.

# This script downloads and opens a Gist from a URL in the clipboard.
# It's meant to be put in the editor's actions menu.
#
# It works with "raw" and "web" gist URLs, but not with gists that
# contain multiple files or non-Python files.
# 
# If a file already exists, a dialog is shown that asks whether the
# new file should be renamed automatically.

import clipboard
import editor
import console
import re
import os

class InvalidGistURLError (Exception): pass
class MultipleFilesInGistError (Exception): pass
class NoFilesInGistError (Exception): pass
class GistDownloadError (Exception): pass

def download_gist(gist_url):
	# Returns a 2-tuple of filename and content
	# console.show_activity()
	raw_match = re.match('http(s?)://raw.github.com/gist/', gist_url)
	if raw_match:
		import requests
		from urlparse import urlparse
		filename = os.path.split(urlparse(gist_url).path)[1]
		try:
			r = requests.get(gist_url)
			content = r.text
			return filename, content
		except:
			raise GistDownloadError()
	else:
		gist_id_match = re.match('http(s?)://gist.github.com/([0-9a-f]*)', gist_url)
		if gist_id_match:
			import requests
			gist_id = gist_id_match.group(2)
			json_url = 'https://api.github.com/gists/' + gist_id
			try:
				import json
				gist_json = requests.get(json_url).text
				gist_info = json.loads(gist_json)
				files = gist_info['files']
			except:
				raise GistDownloadError()
			py_files = []
			for file_info in files.values():
				lang =  file_info.get('language', None)
				if lang != 'Python':
					continue 
				py_files.append(file_info)
			if len(py_files) > 1:
				raise MultipleFilesInGistError()
			elif len(py_files) == 0:
				raise NoFilesInGistError()
			else:
				file_info = py_files[0]
				filename = file_info['filename']
				content = file_info['content']
				return filename, content
		else:
			raise InvalidGistURLError()

def main():
	gist_url = clipboard.get()
	try:
		filename, content = download_gist(gist_url)
		content = content.encode('ascii', 'ignore')
		if os.path.isfile(filename):
			i = console.alert('File exists', 'A file with the name ' + filename + 
			                  ' already exists in your library.',
			                  'Auto Rename')
			if i == 1:
				editor.make_new_file(filename, content)
		else:
			editor.make_new_file(filename, content)
	except InvalidGistURLError:
		console.alert('No Gist URL',
		              'The clipboard doesn\'t seem to contain a valid Gist URL.',
		              'OK')
	except MultipleFilesInGistError:
		console.alert('Multiple Files', 'This Gist contains multiple ' +
			            'Python files, which isn\'t currently supported.')
	except NoFilesInGistError:
		console.alert('No Python Files', 'This Gist contains no Python files.')
	except GistDownloadError:
		console.alert('Error', 'The Gist could not be downloaded.')
		
if __name__ == '__main__':
	main()



;

public by watmough  508  0  3  0

Insert a custom browser tab into Pythonista

Insert a custom browser tab into Pythonista: Add Web Tab.py
# coding: utf-8
from Foundation import *
from QuartzCore import *
from UIKit import *

import console

WKWebView = ObjCClass('WKWebView')
	
@on_main_thread
def main():
	rootVC = UIApplication.sharedApplication().windows()[0].rootViewController()
	tabVC = rootVC.detailViewController()

	methods = [openURL, search]
	protocols = ['OMTabContent']
	CustomViewController = create_objc_class('CustomViewController', UIViewController, methods=methods, protocols=protocols)
	
	vc = CustomViewController.new()
	vc.title = 'Web'
	
	urlBarItem = UIBarButtonItem.alloc().initWithImage_style_target_action_(UIImage.imageNamed_('Textures/ionicons-link-24'),0,vc,sel('openURL'))
	searchBarItem = UIBarButtonItem.alloc().initWithImage_style_target_action_(UIImage.imageNamed_('Textures/ionicons-search-24'),0,vc,sel('search'))

	vc.navigationItem().rightBarButtonItems = [urlBarItem, searchBarItem]
	
	webView = WKWebView.new()
	webView.loadRequest_(NSURLRequest.requestWithURL_(NSURL.URLWithString_('http://www.google.com')))
	vc.view = webView

	tabVC.addTabWithViewController_(vc)
	
def openURL(_self, _cmd):
	address = console.input_alert('Open URL')
	if len(address) > 0:
		ObjCInstance(_self).view().loadRequest_(NSURLRequest.requestWithURL_(NSURL.URLWithString_(address)))
	
def search(_self, _cmd):
	term = console.input_alert('Search')
	if len(term) > 0:
		ObjCInstance(_self).view().loadRequest_(NSURLRequest.requestWithURL_(NSURL.URLWithString_('http://google.com/search?q='+term)))
	
if __name__ == '__main__':
	main()

;