code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
self.logger.debug("shuffle command") if not self.state == 'ready': return self.statuslog.debug("Shuffling") random.shuffle(self.queue) self.update_queue() self.statuslog.debug("Shuffled")
async def shuffle(self)
The shuffle command
5.953297
5.141847
1.157813
if loop_value not in ['on', 'off', 'shuffle']: self.statuslog.error("Loop value must be `off`, `on`, or `shuffle`") return self.loop_type = loop_value if self.loop_type == 'on': self.statuslog.info("Looping on") elif self.loop_type == 'off': ...
async def set_loop(self, loop_value)
Updates the loop value, can be 'off', 'on', or 'shuffle
2.465473
2.161606
1.140575
self.logger.debug("volume command") if self.state != 'ready': return logger.debug("Volume command received") if value == '+': if self.volume < 100: self.statuslog.debug("Volume up") self.volume = (10 * (self.volume // 1...
async def setvolume(self, value)
The volume command Args: value (str): The value to set the volume to
2.041068
2.006222
1.017369
# Update the volume data = datatools.get_data() data["discord"]["servers"][self.server_id][_data.modulename]["volume"] = self.volume datatools.write_data(data)
def write_volume(self)
Writes the current volume to the data.json
9.501169
8.200633
1.15859
self.logger.debug("movehere command") # Delete the old message await self.embed.delete() # Set the channel to this channel self.embed.channel = channel # Send a new embed to the channel await self.embed.send() # Re-add the reactions awai...
async def movehere(self, channel)
Moves the embed message to a new channel; can also be used to move the musicplayer to the front Args: channel (discord.Channel): The channel to move to
5.887609
4.962394
1.186445
data = datatools.get_data() data["discord"]["servers"][self.server_id][_data.modulename]["topic_id"] = channel.id datatools.write_data(data) self.topicchannel = channel await self.set_topic(self.topic) await client.send_typing(channel) embed = ui_embed....
async def set_topic_channel(self, channel)
Set the topic channel for this server
6.204651
5.732705
1.082325
try: if self.topicchannel: await client.edit_channel(self.topicchannel, topic="") except Exception as e: logger.exception(e) self.topicchannel = None logger.debug("Clearing topic channel") data = datatools.get_data() data...
async def clear_topic_channel(self, channel)
Set the topic channel for this server
5.420691
5.132444
1.056162
if self.vready: logger.warning("Attempt to init voice when already initialised") return if self.state != 'starting': logger.error("Attempt to init from wrong state ('{}'), must be 'starting'.".format(self.state)) return self.logger.debu...
async def vsetup(self, author)
Creates the voice client Args: author (discord.Member): The user that the voice ui will seek
3.150619
3.103496
1.015184
if self.mready: logger.warning("Attempt to init music when already initialised") return if self.state != 'starting': logger.error("Attempt to init from wrong state ('{}'), must be 'starting'.".format(self.state)) return self.logger.debu...
async def msetup(self, text_channel)
Creates the gui Args: text_channel (discord.Channel): The channel for the embed ui to run in
6.712276
5.821869
1.152942
self.logger.debug("Creating new embed ui object") # Initial queue display queue_display = [] for i in range(self.queue_display): queue_display.append("{}. ---\n".format(str(i + 1))) # Initial datapacks datapacks = [ ("Now playing", "---...
def new_embed_ui(self)
Create the embed UI object and save it to self
2.497576
2.464261
1.01352
self.statuslog.info("Loading buttons") for e in ("⏯", "⏮", "⏹", "⏭", "🔀", "🔉", "🔊"): try: if self.embed is not None: await client.add_reaction(self.embed.sent_embed, e) except discord.DiscordException as e: logger.ex...
async def add_reactions(self)
Adds the reactions buttons to the current message
4.183209
3.883838
1.077081
if query is None or query == "": return self.statuslog.info("Parsing {}".format(query)) self.logger.debug("Enqueueing from query") indexnum = None if queue_index is not None: try: indexnum = int(queue_index) - 1 exce...
async def enqueue(self, query, queue_index=None, stop_current=False, shuffle=False)
Queues songs based on either a YouTube search or a link Args: query (str): Either a search term or a link queue_index (str): The queue index to enqueue at (None for end) stop_current (bool): Whether to stop the current song after the songs are queued shuffle (boo...
3.516958
3.566933
0.98599
if index is not None and len(self.queue) > 0: if index < 0 or index >= len(self.queue): if len(self.queue) == 1: self.statuslog.error("Play index must be 1 (1 song in queue)") return else: self.stat...
def parse_query(self, query, index, stop_current, shuffle)
Parses a query and adds it to the queue Args: query (str): Either a search term or a link index (int): The index to enqueue at (None for end) stop_current (bool): Whether to stop the current song after the songs are queued shuffle (bool): Whether to shuffle the a...
2.518652
2.453348
1.026618
self.logger.debug("Updating queue display") queue_display = [] for i in range(self.queue_display): try: if len(self.queue[i][1]) > 40: songname = self.queue[i][1][:37] + "..." else: songname = self.que...
def update_queue(self)
Updates the queue in the music player
3.047887
2.772081
1.099494
self.topic = topic try: if self.topicchannel: await client.edit_channel(self.topicchannel, topic=topic) except Exception as e: logger.exception(e)
async def set_topic(self, topic)
Sets the topic for the topic channel
3.990576
3.11085
1.282793
self.logger.debug("Clearing cache") if os.path.isdir(self.songcache_dir): for filename in os.listdir(self.songcache_dir): file_path = os.path.join(self.songcache_dir, filename) try: if os.path.isfile(file_path): ...
def clear_cache(self)
Removes all files from the songcache dir
2.107954
1.804132
1.168403
if not os.path.isdir(self.songcache_next_dir): return logger.debug("Moving next cache") files = os.listdir(self.songcache_next_dir) for f in files: try: os.rename("{}/{}".format(self.songcache_next_dir, f), "{}/{}".format(self.songcache_d...
def move_next_cache(self)
Moves files in the 'next' cache dir to the root
2.549497
2.360905
1.079881
if d['status'] == 'downloading': self.play_empty() if "elapsed" in d: if d["elapsed"] > self.current_download_elapsed + 4: self.current_download_elapsed = d["elapsed"] current_download = 0 current_down...
def ytdl_progress_hook(self, d)
Called when youtube-dl updates progress
2.399318
2.378313
1.008832
if self.vclient: if self.streamer: self.streamer.volume = 0 self.vclient.play_audio("\n".encode(), encode=False)
def play_empty(self)
Play blank audio to let Discord know we're still here
11.196185
8.785538
1.274388
dl_ydl_opts = dict(ydl_opts) dl_ydl_opts["progress_hooks"] = [self.ytdl_progress_hook] dl_ydl_opts["outtmpl"] = self.output_format # Move the songs from the next cache to the current cache self.move_next_cache() self.state = 'ready' self.play_empty() ...
def download_next_song(self, song)
Downloads the next song and starts playing it
3.924067
3.876109
1.012373
if len(self.queue) == 0: return cache_ydl_opts = dict(ydl_opts) cache_ydl_opts["outtmpl"] = self.output_format_next with youtube_dl.YoutubeDL(cache_ydl_opts) as ydl: try: url = self.queue[0][0] ydl.download([url]) ...
def download_next_song_cache(self)
Downloads the next song in the queue to the cache
2.810804
2.681626
1.048172
self.current_download_elapsed = 0 self.streamer = self.vclient.create_ffmpeg_player(filepath, after=self.vafter_ts) self.state = "ready" await self.setup_streamer() try: # Read from the info json info_filename = "{}.info.json".format(filepath) ...
async def create_ffmpeg_player(self, filepath)
Creates a streamer that plays from a file
4.197605
4.088032
1.026803
self.current_download_elapsed = 0 self.streamer = await self.vclient.create_ytdl_player(url, ytdl_options=opts, after=self.vafter_ts) self.state = "ready" await self.setup_streamer() self.nowplayinglog.debug(self.streamer.title) self.nowplayingauthorlog.debug(...
async def create_stream_player(self, url, opts=ydl_opts)
Creates a streamer that plays from a URL
4.882807
4.916753
0.993096
self.streamer.volume = self.volume / 100 self.streamer.start() self.pause_time = None self.vclient_starttime = self.vclient.loop.time() # Cache next song self.logger.debug("Caching next song") dl_thread = threading.Thread(target=self.download_next_song_...
async def setup_streamer(self)
Sets up basic defaults for the streamer
5.781162
5.622324
1.028251
logger.debug("Song finishing") future = asyncio.run_coroutine_threadsafe(self.vafter(), client.loop) try: future.result() except Exception as e: logger.exception(e)
def vafter_ts(self)
Function that is called after a song finishes playing
5.363763
4.070711
1.317648
self.logger.debug("Finished playing a song") if self.state != 'ready': self.logger.debug("Returning because player is in state {}".format(self.state)) return self.pause_time = None if self.vclient_task: loop = asyncio.get_event_loop() ...
async def vafter(self)
Function that is called after a song finishes playing
3.579737
3.300544
1.08459
# Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() if not data["discord"]["servers"][server.id][_data.modulename]["activated"]: return # Only reply to server messages and...
async def on_message(message)
The on_message event handler for this module Args: message (discord.Message): Input message
2.890134
2.851386
1.013589
data = datatools.get_data() if "google_api_key" not in data["discord"]["keys"]: logger.warning("No API key found with name 'google_api_key'") logger.info("Please add your Google API key with name 'google_api_key' " "in data.json to use YouTube features of the music modul...
def build_yt_api()
Build the YouTube API for future use
3.972723
3.874193
1.025432
data = datatools.get_data() if "soundcloud_client_id" not in data["discord"]["keys"]: logger.warning("No API key found with name 'soundcloud_client_id'") logger.info("Please add your SoundCloud client id with name 'soundcloud_client_id' " "in data.json to use Soundcloud ...
def build_sc_api()
Build the SoundCloud API for future use
4.241187
3.914825
1.083366
data = datatools.get_data() if "spotify_client_id" not in data["discord"]["keys"]: logger.warning("No API key found with name 'spotify_client_id'") logger.info("Please add your Spotify client id with name 'spotify_client_id' " "in data.json to use Spotify features of the...
def build_spotify_api()
Build the Spotify API for future use
2.39508
2.343126
1.022173
queue = [] # Search YouTube search_result = ytdiscoveryapi.search().list( q=query, part="id,snippet", maxResults=1, type="video,playlist" ).execute() if not search_result["items"]: return [] # Get video/playlist title title = s...
def get_ytvideos(query, ilogger)
Gets either a list of videos from a playlist or a single video, using the first result of a YouTube search Args: query (str): The YouTube search query ilogger (logging.logger): The logger to log API calls to Returns: queue (list): The items obtained from the YouTube search
2.500821
2.49988
1.000377
m, s = divmod(duration, 60) h, m = divmod(m, 60) return "%d:%02d:%02d" % (h, m, s)
def duration_to_string(duration)
Converts a duration to a string Args: duration (int): The duration in seconds to convert Returns s (str): The duration as a string
1.800046
1.907866
0.943487
if "extractor_key" in info: source = info["extractor_key"] lower_source = source.lower() for key in SOURCE_TO_NAME: lower_key = key.lower() if lower_source == lower_key: source = SOURCE_TO_NAME[lower_key] if source != "Generic": ...
def parse_source(info)
Parses the source info from an info dict generated by youtube-dl Args: info (dict): The info dict to parse Returns: source (str): The source of this song
3.053095
2.768709
1.102714
# Prevent tampering with flip punct = tamperdict = str.maketrans('', '', punct) tamperproof = content.translate(tamperdict) # Unflip if "(╯°□°)╯︵" in tamperproof: # For tables if "┻┻" in tamperproof: # Calculate table length length = 0 ...
def flipcheck(content)
Checks a string for anger and soothes said anger Args: content (str): The message to be flipchecked Returns: putitback (str): The righted table or text
4.304721
4.098611
1.050288
logger.debug("Getting new botcust2") # Set up http request packages params = { 'botid': 'f6a012073e345a08', 'amp;skin': 'chat' } headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate...
def get_botcust2()
Gets a botcust2, used to identify a speaker with Mitsuku Returns: botcust2 (str): The botcust2 identifier
2.973293
2.831616
1.050034
logger.debug("Getting Mitsuku reply") # Set up http request packages params = { 'botid': 'f6a012073e345a08', 'amp;skin': 'chat' } headers = { 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.8', 'Cache-Control': 'max-age=0', ...
def query(botcust2, message)
Sends a message to Mitsuku and retrieves the reply Args: botcust2 (str): The botcust2 identifier message (str): The message to send to Mitsuku Returns: reply (str): The message Mitsuku sent back
2.589856
2.499697
1.036068
# Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() if not data["discord"]["servers"][server.id][_data.modulename]["activated"]: return # Only reply to server messages and...
async def on_message(message)
The on_message event handler for this module Args: message (discord.Message): Input message
2.301347
2.29653
1.002097
import discord import asyncio # Create client logger.debug("Creating Discord client") asyncio.set_event_loop(loop) client = discord.Client() from . import _client _client.client = client from .. import datatools if datatools.has_data(): data = datatools.get_data() ...
def start(token, client_id, loop, on_ready_handler=None)
Start the Discord client and log Modis into Discord.
2.357196
2.334225
1.009841
import os import importlib event_handlers = { "on_ready": [], "on_resume": [], "on_error": [], "on_message": [], "on_socket_raw_receive": [], "on_socket_raw_send": [], "on_message_delete": [], "on_message_edit": [], "on_reaction_...
def _get_event_handlers()
Gets dictionary of event handlers and the modules that define them Returns: event_handlers (dict): Contains "all", "on_ready", "on_message", "on_reaction_add", "on_error"
1.949412
1.923614
1.013411
if key is None or key == "": logger.error("Key cannot be empty") if value is None or value == "": logger.error("Value cannot be empty") from .. import datatools data = datatools.get_data() if "keys" not in data["discord"]: data["discord"]["keys"] = {} is_key_new...
def add_api_key(key, value)
Adds a key to the bot's data Args: key: The name of the key to add value: The value for the key
2.463665
2.477262
0.994511
# Create embed UI object gui = ui_embed.UI( channel, title, "", modulename=modulename, datapacks=datapacks ) return gui
def success(channel, title, datapacks)
Creates an embed UI containing the help message Args: channel (discord.Channel): The Discord channel to bind the embed to title (str): The title of the embed datapacks (list): The hex value Returns: ui (ui_embed.UI): The embed UI object
10.057536
6.261783
1.606178
# Create embed UI object gui = ui_embed.UI( channel, "Too much help", "{} is too helpful! Try trimming some of the help messages.".format(title), modulename=modulename ) return gui
def http_exception(channel, title)
Creates an embed UI containing the 'too long' error message Args: channel (discord.Channel): The Discord channel to bind the embed to title (str): The title of the embed Returns: ui (ui_embed.UI): The embed UI object
20.448622
10.698138
1.911419
puts("Configuring Tarbell. Press ctrl-c to bail out!") # Check if there's settings configured settings = Settings() path = settings.path prompt = True if len(args): prompt = False config = _get_or_create_config(path) if prompt or "drive" in args: config.update(_s...
def tarbell_configure(command, args)
Tarbell configuration routine.
4.385233
4.449092
0.985647
dirname = os.path.dirname(path) filename = os.path.basename(path) try: os.makedirs(dirname) except OSError: pass try: with open(path, 'r+') as f: if os.path.isfile(path): puts("{0} already exists, backing up".format(colored.green(path))) ...
def _get_or_create_config(path, prompt=True)
Get or create a Tarbell configuration directory.
3.251756
3.308632
0.98281
ret = {} if prompt: use = raw_input("\nWould you like to use Google spreadsheets [Y/n]? ") if use.lower() != "y" and use != "": return settings dirname = os.path.dirname(path) path = os.path.join(dirname, "client_secrets.json") write_secrets = True if os.path.i...
def _setup_google_spreadsheets(settings, path, prompt=True)
Set up a Google spreadsheet.
4.190787
4.153405
1.009
default_path = os.path.expanduser(os.path.join("~", "tarbell")) projects_path = raw_input("\nWhat is your Tarbell projects path? [Default: {0}, 'none' to skip] ".format(default_path)) if projects_path == "": projects_path = default_path if projects_path.lower() == 'none': puts("\n- ...
def _setup_tarbell_project_path(settings, path, prompt=True)
Prompt user to set up project path.
3.132306
3.016257
1.038474
project_templates = [{ "name": "Basic Bootstrap 3 template", "url": "https://github.com/tarbell-project/tarbell-template", }, { "name": "Searchable map template", "url": "https://github.com/tarbell-project/tarbell-map-template", }, { "name": "Tarbell template wal...
def _setup_default_templates(settings, path, prompt=True)
Add some (hardcoded) default templates.
4.11486
3.868935
1.063564
target = os.path.join(path, filename) if os.path.isfile(target): dt = datetime.now() new_filename = ".{0}.{1}.{2}".format( filename, dt.isoformat(), "backup" ) destination = os.path.join(path, new_filename) puts("- Backing up {0} to {1}".format( ...
def _backup(path, filename)
Backup a file.
3.188492
3.161486
1.008542
# unicodification if type(value) != text_type: value = value.decode('utf-8', 'ignore') # overwrite chararcter mapping char_map.update(overwrite_char_map) # try to replace chars value = re.sub('[^a-zA-Z0-9\\s\\-]{1}', replace_char, value) value = slugify(value) return va...
def slughifi(value, overwrite_char_map={})
High Fidelity slugify - slughifi.py, v 0.1 Examples : >>> text = 'C\'est déjà l\'été.' >>> slughifi(text) 'cest-deja-lete' >>> slughifi(text, overwrite_char_map={u'\': '-',}) 'c-est-deja-l-ete' >>> slughifi(text, do_slugify=False) "C'est deja l'ete." ...
4.196535
4.150454
1.011103
if not is_werkzeug_process(): try: return _puts(s, newline, stream) except UnicodeEncodeError: return _puts(s.encode(sys.stdout.encoding), newline, stream)
def puts(s='', newline=True, stream=STDOUT)
Wrap puts to avoid getting called twice by Werkzeug reloader.
4.139122
3.244381
1.275782
try: if l[idx]: return l[idx] else: return default except IndexError: return default
def list_get(l, idx, default=None)
Get from a list with an optional default value.
2.678545
2.669108
1.003536
sentences = [] for index, sentence in enumerate(s.split('. ')): padding = '' if index > 0: padding = ' ' * (pad + 1) if sentence.endswith('.'): sentence = sentence[:-1] sentences.append('%s %s.' % (padding, sentence.strip())) return "\n".join(sent...
def split_sentences(s, pad=0)
Split sentences for formatting.
2.919621
2.766328
1.055414
dirname = os.path.dirname(path) if not os.path.exists(dirname): os.makedirs(dirname)
def ensure_directory(path)
Ensure directory exists for a given file path.
1.911357
2.002734
0.954374
sys.stdout.flush() sys.stderr.write("\n{0!s}: {1}".format(colored.red("Error"), msg + '\n'))
def show_error(msg)
Displays error message.
6.797616
7.198706
0.944283
_srtp_assert(lib.srtp_add_stream(self._srtp[0], policy._policy))
def add_stream(self, policy)
Add a stream to the SRTP session, applying the given `policy` to the stream. :param policy: :class:`Policy`
14.794142
13.756671
1.075416
_srtp_assert(lib.srtp_remove_stream(self._srtp[0], htonl(ssrc)))
def remove_stream(self, ssrc)
Remove the stream with the given `ssrc` from the SRTP session. :param ssrc: :class:`int`
11.416483
11.375182
1.003631
data = {} workbook = xlrd.open_workbook(file_contents=content) worksheets = [w for w in workbook.sheet_names() if not w.startswith('_')] for worksheet_name in worksheets: if worksheet_name.startswith('_'): continue worksheet = workbook.sheet_by_name(worksheet_name) ...
def process_xlsx(content)
Turn Excel file contents into Tarbell worksheet data
2.726949
2.599309
1.049105
for k, v in data['values'].items(): if not data.get(k): data[k] = v else: puts("There is both a worksheet and a " "value named '{0}'. The worksheet data " "will be preserved.".format(k)) data.pop("values", None) return data
def copy_global_values(data)
Copy values worksheet into global namespace.
5.787867
4.788786
1.208629
headers = {} cell_idx = 0 while cell_idx < worksheet.ncols: cell_type = worksheet.cell_type(0, cell_idx) if cell_type == 1: header = slughifi(worksheet.cell_value(0, cell_idx)) if not header.startswith("_"): headers[cell_idx] = header cell...
def make_headers(worksheet)
Make headers from worksheet
2.851074
2.778429
1.026146
data = [] row_idx = 1 while row_idx < worksheet.nrows: cell_idx = 0 row_dict = {} while cell_idx < worksheet.ncols: cell_type = worksheet.cell_type(row_idx, cell_idx) if cell_type in VALID_CELL_TYPES: cell_value = worksheet.cell_value(row_...
def make_worksheet_data(headers, worksheet)
Make data from worksheet
2.841851
2.801182
1.014518
response.cache_control.max_age = 0 response.cache_control.no_cache = True response.cache_control.must_revalidate = True response.cache_control.no_store = True return response
def never_cache_preview(self, response)
Ensure preview is never cached
1.772355
1.617481
1.09575
for function in self.hooks[hook]: function.__call__(*args, **kwargs)
def call_hook(self, hook, *args, **kwargs)
Calls each registered hook
5.587897
5.522636
1.011817
base = None # Slightly ugly DRY violation for backwards compatibility with old # "_base" convention if os.path.isdir(os.path.join(path, "_blueprint")): base_dir = os.path.join(path, "_blueprint/") # Get the blueprint template and register it as a bluepri...
def _get_base(self, path)
Get project blueprint
2.571948
2.523041
1.019384
base = self._get_base(path) filename, pathname, description = imp.find_module('tarbell_config', [path]) project = imp.load_module('project', filename, pathname, description) try: self.key = project.SPREADSHEET_KEY self.client = get_drive_api() e...
def load_project(self, path)
Load a Tarbell project
3.178164
3.106509
1.023066
filepath = None mimetype = None for root, dirs, files in self.filter_files(self.path): # Does it exist in error path? error_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'error_templates', path) try: with open(error_...
def _resolve_path(self, path)
Resolve static file paths
2.692037
2.63463
1.02179
if not self.project.CREATE_JSON: # nothing to see here, but the right mimetype return jsonify() if not self.data: # this sets site.data by spreadsheet or gdoc self.get_context(publish) return jsonify(self.data)
def data_json(self, extra_context=None, publish=False)
Serve site context as JSON. Useful for debugging.
20.696764
16.351294
1.265757
try: self.call_hook("preview", self) if path is None: path = 'index.html' # Detect files filepath, mimetype = self._resolve_path(path) # Serve dynamic if filepath and mimetype and mimetype in self.project.TEMPLAT...
def preview(self, path=None, extra_context=None, publish=False)
Serve up a project path
2.910424
2.904639
1.001992
context = self.project.DEFAULT_CONTEXT try: file = self.project.CONTEXT_SOURCE_FILE # CSV if re.search(r'(csv|CSV)$', file): context.update(self.get_context_from_csv()) # Excel if re.search(r'(xlsx|XLSX|xls|XLS)$', file...
def get_context(self, publish=False)
Use optional CONTEXT_SOURCE_FILE setting to determine data source. Return the parsed data. Can be an http|https url or local file. Supports csv and excel files.
3.720543
2.973658
1.251167
if re.search('^(http|https)://', self.project.CONTEXT_SOURCE_FILE): resp = requests.get(self.project.CONTEXT_SOURCE_FILE) content = resp.content else: try: with open(self.project.CONTEXT_SOURCE_FILE) as xlsxfile: content = ...
def get_context_from_xlsx(self)
Get context from an Excel file
2.964094
2.926321
1.012908
if re.search('^(http|https)://', self.project.CONTEXT_SOURCE_FILE): data = requests.get(self.project.CONTEXT_SOURCE_FILE) reader = csv.reader( data.iter_lines(), delimiter=',', quotechar='"') ret = {rows[0]: rows[1] for rows in reader} else: ...
def get_context_from_csv(self)
Open CONTEXT_SOURCE_FILE, parse and return a context
2.124343
1.978838
1.073531
try: start = int(time.time()) if not self.data or start > self.expires: self.data = self._get_context_from_gdoc(self.project.SPREADSHEET_KEY) end = int(time.time()) ttl = getattr(self.project, 'SPREADSHEET_CACHE_TTL', ...
def get_context_from_gdoc(self)
Wrap getting context from Google sheets in a simple caching mechanism.
3.725437
3.382489
1.101389
try: content = self.export_xlsx(key) data = process_xlsx(content) if 'values' in data: data = copy_global_values(data) return data except BadStatusLine: # Stale connection, reset API and data puts("Connectio...
def _get_context_from_gdoc(self, key)
Create a Jinja2 context from a Google spreadsheet.
7.99379
7.52238
1.062668
spreadsheet_file = self.client.files().get(fileId=key).execute() links = spreadsheet_file.get('exportLinks') downloadurl = links.get('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') resp, content = self.client._http.request(downloadurl) return content
def export_xlsx(self, key)
Download xlsx version of spreadsheet.
2.905639
2.645536
1.098318
self.app.config['BUILD_PATH'] = output_root # use this hook for registering URLs to freeze self.call_hook("generate", self, output_root, extra_context) if output_root is not None: # realpath or this gets generated relative to the tarbell package self.ap...
def generate_static_site(self, output_root=None, extra_context=None)
Bake out static site
8.542717
8.413586
1.015348
excludes = r'|'.join([fnmatch.translate(x) for x in self.project.EXCLUDES]) or r'$.' for root, dirs, files in os.walk(path, topdown=True): dirs[:] = [d for d in dirs if not re.match(excludes, d)] dirs[:] = [os.path.join(root, d) for d in dirs] rel_path = os.p...
def filter_files(self, path)
Exclude files based on blueprint and project configuration as well as hidden files.
2.097207
2.054291
1.020891
# yield blueprint paths first if getattr(self, 'blueprint_name', None): for path in walk_directory(os.path.join(self.path, self.blueprint_name), ignore=self.project.EXCLUDES): yield 'preview', {'path': path} # then yield project paths for path in wal...
def find_files(self)
Find all file paths for publishing, yield (urlname, kwargs)
4.647479
3.817604
1.217381
self.tempdir = tempfile.mkdtemp('s3deploy') for keyname, absolute_path in self.find_file_paths(): self.s3_upload(keyname, absolute_path) shutil.rmtree(self.tempdir, True) return True
def deploy_to_s3(self)
Deploy a directory to an s3 bucket.
4.641601
4.341798
1.06905
mimetype = mimetypes.guess_type(absolute_path) options = {'Content-Type': mimetype[0]} if mimetype[0] is not None and mimetype[0].startswith('text/'): upload = open(absolute_path, 'rb') options['Content-Encoding'] = 'gzip' key_parts = keyname.split('...
def s3_upload(self, keyname, absolute_path)
Upload a file to s3
2.711093
2.73133
0.992591
paths = [] for root, dirs, files in os.walk(self.directory, topdown=True): rel_path = os.path.relpath(root, self.directory) for f in files: if rel_path == '.': path = (f, os.path.join(root, f)) else: ...
def find_file_paths(self)
A generator function that recursively finds all files in the upload directory.
1.77213
1.71744
1.031843
settings = Settings() if settings.credentials: return get_drive_api_from_file(settings.credentials_path) if settings.client_secrets: return get_drive_api_from_client_secrets(settings.client_secrets_path)
def get_drive_api()
Get drive API client based on settings.
2.911695
2.636927
1.1042
storage = keyring_storage.Storage('tarbell', getpass.getuser()) credentials = None if not reset_creds: credentials = storage.get() if path and not credentials: flow = client.flow_from_clientsecrets(path, scope=OAUTH_SCOPE) credentials = tools.run_flow(flow, storage, flags) ...
def get_drive_api_from_client_secrets(path, reset_creds=False)
Reads the local client secrets file if available (otherwise, opens a browser tab to walk through the OAuth 2.0 process, and stores the client secrets for future use) and then authorizes those credentials. Returns a Google Drive API service object.
3.957547
4.132975
0.957554
f = open(path) credentials = client.OAuth2Credentials.from_json(f.read()) return _get_drive_api(credentials)
def get_drive_api_from_file(path)
Open file with OAuth tokens.
3.58801
2.943418
1.218994
http = httplib2.Http() http = credentials.authorize(http) service = discovery.build('drive', 'v2', http=http) service.credentials = credentials # duck punch service obj. with credentials return service
def _get_drive_api(credentials)
For a given set of credentials, return a drive API object.
4.306924
4.129331
1.043008
command = Command.lookup(args.get(0)) if len(args) == 0 or args.contains(('-h', '--help', 'help')): display_info(args) sys.exit(1) elif args.contains(('-v', '--version')): display_version() sys.exit(1) elif command: arg = args.get(0) args.remove(ar...
def main()
Primary Tarbell command dispatch.
3.633242
3.429517
1.059404
puts('\nTarbell: Simple web publishing\n') puts('Usage: {0}\n'.format(colored.cyan('tarbell <command>'))) puts('Commands:\n') for command in Command.all_commands(): usage = command.usage or command.name help = command.help or '' puts('{0} {1}'.format( colored.ye...
def display_info(args)
Displays Tarbell info.
5.230482
4.854829
1.077377
output_root = None with ensure_settings(command, args) as settings, ensure_project(command, args) as site: if not skip_args: output_root = list_get(args, 0, False) if output_root: is_folder = os.path.exists(output_root) else: pu...
def tarbell_generate(command, args, skip_args=False, extra_context=None, quiet=False)
Generate static files.
4.209682
4.223467
0.996736
with ensure_settings(command, args) as settings: project_url = args.get(0) puts("\n- Getting project information for {0}".format(project_url)) project_name = project_url.split("/").pop() error = None # Create a tempdir and clone tempdir = tempfile.mkdtemp() ...
def tarbell_install(command, args)
Install a project.
4.668844
4.677901
0.998064
with ensure_settings(command, args) as settings: name = None error = None template_url = args.get(0) matches = [template for template in settings.config["project_templates"] if template.get("url") == template_url] tempdir = tempfile.mkdtemp() if matches: ...
def tarbell_install_blueprint(command, args)
Install a project template.
4.079836
4.000357
1.019868
with ensure_settings(command, args) as settings: projects_path = settings.config.get("projects_path") if not projects_path: show_error("{0} does not exist".format(projects_path)) sys.exit() puts("Listing projects in {0}\n".format( colored.yellow(proj...
def tarbell_list(command, args)
List tarbell projects.
2.901896
2.889205
1.004393
with ensure_settings(command, args) as settings: puts("\nAvailable project templates\n") _list_templates(settings) puts("")
def tarbell_list_templates(command, args)
List available Tarbell blueprints.
9.86818
11.020662
0.895425
with ensure_settings(command, args) as settings, ensure_project(command, args) as site: bucket_name = list_get(args, 0, "staging") try: bucket_url = S3Url(site.project.S3_BUCKETS[bucket_name]) except KeyError: show_error( "\nThere's no bucket con...
def tarbell_publish(command, args)
Publish to s3.
3.726612
3.72419
1.00065
with ensure_settings(command, args) as settings: # Set it up and make the directory name = _get_project_name(args) puts("Creating {0}".format(colored.cyan(name))) path = _get_path(name, settings) _mkdir(path) try: _newproject(command, path, name, set...
def tarbell_newproject(command, args)
Create new Tarbell project.
4.317109
4.398706
0.98145
with ensure_project(command, args) as site: with ensure_settings(command, args) as settings: address = list_get(args, 0, "").split(":") ip = list_get(address, 0, settings.config['default_server_ip']) port = int(list_get(address, 1, settings.config['default_server_por...
def tarbell_serve(command, args)
Serve the current Tarbell project.
4.887783
4.878518
1.001899
with ensure_settings(command, args) as settings: projects_path = settings.config.get("projects_path") if not projects_path: show_error("{0} does not exist".format(projects_path)) sys.exit() project = args.get(0) args.remove(project) project_path =...
def tarbell_switch(command, args)
Switch to a project.
3.115329
3.132308
0.994579
with ensure_settings(command, args) as settings, ensure_project(command, args) as site: puts("Updating to latest blueprint\n") git = sh.git.bake(_cwd=site.base.base_dir) # stash then pull puts(colored.yellow("Stashing local changes")) puts(git.stash()) puts(co...
def tarbell_update(command, args)
Update the current tarbell project.
7.858861
8.158681
0.963251
with ensure_settings(command, args) as settings, ensure_project(command, args) as site: show_error("Not implemented!")
def tarbell_unpublish(command, args)
Delete a project.
11.554045
13.661534
0.845736
with ensure_settings(command, args) as settings, ensure_project(command, args) as site: try: # First, try to get the Google Spreadsheet URL spreadsheet_url = _google_spreadsheet_url(site.project.SPREADSHEET_KEY) except AttributeError: # The project doesn't se...
def tarbell_spreadsheet(command, args)
Open context spreadsheet
6.002113
5.938141
1.010773
if path_or_url.startswith('http'): # Remote CSV. Just return the URL return path_or_url if path_or_url.startswith('/'): # Absolute path return "file://" + path_or_url return "file://" + os.path.join(os.path.realpath(os.getcwd()), path_or_url)
def _context_source_file_url(path_or_url)
Returns a URL for a remote or local context CSV file
2.930269
2.458476
1.191904
key = None title = _get_project_title() template = _get_template(settings) # Init repo git = sh.git.bake(_cwd=path) puts(git.init()) if template.get("url"): # Create submodule puts(git.submodule.add(template['url'], '_blueprint')) puts(git.submodule.update(*['-...
def _newproject(command, path, name, settings)
Helper to create new project.
4.04471
4.02488
1.004927
locations = [os.path.join(path, "_blueprint"), os.path.join(path, "_base"), path] success = True for location in locations: try: with open(os.path.join(location, "requirements.txt")): puts("\nRequirements file found at {0}".format(os.path.join(location, "requirement...
def _install_requirements(path)
Install a blueprint's requirements.txt
3.882927
3.691368
1.051894