idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
41,300 | def new_embed_ui ( self ) : self . logger . debug ( "Creating new embed ui object" ) queue_display = [ ] for i in range ( self . queue_display ) : queue_display . append ( "{}. ---\n" . format ( str ( i + 1 ) ) ) datapacks = [ ( "Now playing" , "---" , False ) , ( "Author" , "---" , True ) , ( "Source" , "---" , True )... | Create the embed UI object and save it to self |
41,301 | async def enqueue ( self , query , queue_index = None , stop_current = False , shuffle = False ) : 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 ( qu... | Queues songs based on either a YouTube search or a link |
41,302 | def parse_query ( self , query , index , stop_current , shuffle ) : 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 . statuslog . error ( "Play inde... | Parses a query and adds it to the queue |
41,303 | def update_queue ( self ) : 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 . queue [ i ] [ 1 ] except IndexError : songname = "--... | Updates the queue in the music player |
41,304 | async def set_topic ( self , topic ) : self . topic = topic try : if self . topicchannel : await client . edit_channel ( self . topicchannel , topic = topic ) except Exception as e : logger . exception ( e ) | Sets the topic for the topic channel |
41,305 | def clear_cache ( self ) : 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 ) : os . unlink ( file_path ) except Perm... | Removes all files from the songcache dir |
41,306 | def move_next_cache ( self ) : 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_dir , f )... | Moves files in the next cache dir to the root |
41,307 | def ytdl_progress_hook ( self , d ) : 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_download_total = 0 current_download_eta = 0 if "total_bytes" in d... | Called when youtube - dl updates progress |
41,308 | def play_empty ( self ) : if self . vclient : if self . streamer : self . streamer . volume = 0 self . vclient . play_audio ( "\n" . encode ( ) , encode = False ) | Play blank audio to let Discord know we re still here |
41,309 | def download_next_song ( self , song ) : dl_ydl_opts = dict ( ydl_opts ) dl_ydl_opts [ "progress_hooks" ] = [ self . ytdl_progress_hook ] dl_ydl_opts [ "outtmpl" ] = self . output_format self . move_next_cache ( ) self . state = 'ready' self . play_empty ( ) with youtube_dl . YoutubeDL ( dl_ydl_opts ) as ydl : try : yd... | Downloads the next song and starts playing it |
41,310 | def download_next_song_cache ( self ) : 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 ] ) except : pass | Downloads the next song in the queue to the cache |
41,311 | async def create_ffmpeg_player ( self , filepath ) : 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 : info_filename = "{}.info.json" . format ( filepath ) with open ( info_file... | Creates a streamer that plays from a file |
41,312 | async def create_stream_player ( self , url , opts = ydl_opts ) : 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... | Creates a streamer that plays from a URL |
41,313 | async def setup_streamer ( self ) : self . streamer . volume = self . volume / 100 self . streamer . start ( ) self . pause_time = None self . vclient_starttime = self . vclient . loop . time ( ) self . logger . debug ( "Caching next song" ) dl_thread = threading . Thread ( target = self . download_next_song_cache ) dl... | Sets up basic defaults for the streamer |
41,314 | def build_yt_api ( ) : 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 module" ) r... | Build the YouTube API for future use |
41,315 | def build_sc_api ( ) : 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 featur... | Build the SoundCloud API for future use |
41,316 | def build_spotify_api ( ) : 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 ... | Build the Spotify API for future use |
41,317 | def get_ytvideos ( query , ilogger ) : queue = [ ] search_result = ytdiscoveryapi . search ( ) . list ( q = query , part = "id,snippet" , maxResults = 1 , type = "video,playlist" ) . execute ( ) if not search_result [ "items" ] : return [ ] title = search_result [ "items" ] [ 0 ] [ "snippet" ] [ "title" ] ilogger . inf... | Gets either a list of videos from a playlist or a single video using the first result of a YouTube search |
41,318 | def duration_to_string ( duration ) : m , s = divmod ( duration , 60 ) h , m = divmod ( m , 60 ) return "%d:%02d:%02d" % ( h , m , s ) | Converts a duration to a string |
41,319 | def parse_source ( info ) : 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" : return source if "url" in info and info [ "ur... | Parses the source info from an info dict generated by youtube - dl |
41,320 | def get_botcust2 ( ) : logger . debug ( "Getting new botcust2" ) 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, sdch, br' , 'Accept-Language' : 'en-US,en;q=0.8' , 'C... | Gets a botcust2 used to identify a speaker with Mitsuku |
41,321 | def query ( botcust2 , message ) : logger . debug ( "Getting Mitsuku reply" ) 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' , 'Connection' : 'keep-alive' , 'Content-Length' : str ... | Sends a message to Mitsuku and retrieves the reply |
41,322 | def _get_event_handlers ( ) : 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_add" : [ ] , "on_reaction_remove" : [... | Gets dictionary of event handlers and the modules that define them |
41,323 | def add_api_key ( key , value ) : 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... | Adds a key to the bot s data |
41,324 | def success ( channel , title , datapacks ) : gui = ui_embed . UI ( channel , title , "" , modulename = modulename , datapacks = datapacks ) return gui | Creates an embed UI containing the help message |
41,325 | def http_exception ( channel , title ) : gui = ui_embed . UI ( channel , "Too much help" , "{} is too helpful! Try trimming some of the help messages." . format ( title ) , modulename = modulename ) return gui | Creates an embed UI containing the too long error message |
41,326 | def tarbell_configure ( command , args ) : puts ( "Configuring Tarbell. Press ctrl-c to bail out!" ) 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 ( _setup_google_spreadsheets ( config ... | Tarbell configuration routine . |
41,327 | def _get_or_create_config ( path , prompt = True ) : 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 . ... | Get or create a Tarbell configuration directory . |
41,328 | def _setup_google_spreadsheets ( settings , path , prompt = True ) : 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" ... | Set up a Google spreadsheet . |
41,329 | def _setup_tarbell_project_path ( settings , path , prompt = True ) : 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 = de... | Prompt user to set up project path . |
41,330 | def _backup ( path , filename ) : 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 ... | Backup a file . |
41,331 | def slughifi ( value , overwrite_char_map = { } ) : if type ( value ) != text_type : value = value . decode ( 'utf-8' , 'ignore' ) char_map . update ( overwrite_char_map ) value = re . sub ( '[^a-zA-Z0-9\\s\\-]{1}' , replace_char , value ) value = slugify ( value ) return value . encode ( 'ascii' , 'ignore' ) . decode ... | High Fidelity slugify - slughifi . py v 0 . 1 |
41,332 | def puts ( s = '' , newline = True , stream = STDOUT ) : if not is_werkzeug_process ( ) : try : return _puts ( s , newline , stream ) except UnicodeEncodeError : return _puts ( s . encode ( sys . stdout . encoding ) , newline , stream ) | Wrap puts to avoid getting called twice by Werkzeug reloader . |
41,333 | def list_get ( l , idx , default = None ) : try : if l [ idx ] : return l [ idx ] else : return default except IndexError : return default | Get from a list with an optional default value . |
41,334 | def split_sentences ( s , pad = 0 ) : 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 ... | Split sentences for formatting . |
41,335 | def ensure_directory ( path ) : dirname = os . path . dirname ( path ) if not os . path . exists ( dirname ) : os . makedirs ( dirname ) | Ensure directory exists for a given file path . |
41,336 | def show_error ( msg ) : sys . stdout . flush ( ) sys . stderr . write ( "\n{0!s}: {1}" . format ( colored . red ( "Error" ) , msg + '\n' ) ) | Displays error message . |
41,337 | def add_stream ( self , policy ) : _srtp_assert ( lib . srtp_add_stream ( self . _srtp [ 0 ] , policy . _policy ) ) | Add a stream to the SRTP session applying the given policy to the stream . |
41,338 | def remove_stream ( self , ssrc ) : _srtp_assert ( lib . srtp_remove_stream ( self . _srtp [ 0 ] , htonl ( ssrc ) ) ) | Remove the stream with the given ssrc from the SRTP session . |
41,339 | def process_xlsx ( content ) : 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... | Turn Excel file contents into Tarbell worksheet data |
41,340 | def copy_global_values ( data ) : 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 | Copy values worksheet into global namespace . |
41,341 | def make_headers ( worksheet ) : 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_idx += 1 return he... | Make headers from worksheet |
41,342 | def make_worksheet_data ( headers , worksheet ) : 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_idx , cell_i... | Make data from worksheet |
41,343 | def never_cache_preview ( self , response ) : 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 | Ensure preview is never cached |
41,344 | def call_hook ( self , hook , * args , ** kwargs ) : for function in self . hooks [ hook ] : function . __call__ ( * args , ** kwargs ) | Calls each registered hook |
41,345 | def _get_base ( self , path ) : base = None if os . path . isdir ( os . path . join ( path , "_blueprint" ) ) : base_dir = os . path . join ( path , "_blueprint/" ) if os . path . exists ( os . path . join ( base_dir , "blueprint.py" ) ) : filename , pathname , description = imp . find_module ( 'blueprint' , [ base_dir... | Get project blueprint |
41,346 | def load_project ( self , path ) : 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 ( ) except At... | Load a Tarbell project |
41,347 | def _resolve_path ( self , path ) : filepath = None mimetype = None for root , dirs , files in self . filter_files ( self . path ) : error_path = os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , 'error_templates' , path ) try : with open ( error_path ) : mimetype , encoding = mimetypes . gu... | Resolve static file paths |
41,348 | def data_json ( self , extra_context = None , publish = False ) : if not self . project . CREATE_JSON : return jsonify ( ) if not self . data : self . get_context ( publish ) return jsonify ( self . data ) | Serve site context as JSON . Useful for debugging . |
41,349 | def preview ( self , path = None , extra_context = None , publish = False ) : try : self . call_hook ( "preview" , self ) if path is None : path = 'index.html' filepath , mimetype = self . _resolve_path ( path ) if filepath and mimetype and mimetype in self . project . TEMPLATE_TYPES : context = self . get_context ( pu... | Serve up a project path |
41,350 | def get_context ( self , publish = False ) : context = self . project . DEFAULT_CONTEXT try : file = self . project . CONTEXT_SOURCE_FILE if re . search ( r'(csv|CSV)$' , file ) : context . update ( self . get_context_from_csv ( ) ) if re . search ( r'(xlsx|XLSX|xls|XLS)$' , file ) : context . update ( self . get_conte... | Use optional CONTEXT_SOURCE_FILE setting to determine data source . Return the parsed data . |
41,351 | def get_context_from_xlsx ( self ) : 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 = xlsxfile . read ( ) except I... | Get context from an Excel file |
41,352 | def get_context_from_csv ( self ) : 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 ... | Open CONTEXT_SOURCE_FILE parse and return a context |
41,353 | def get_context_from_gdoc ( self ) : 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' , SPREADSHEET_CACHE_TTL ) self... | Wrap getting context from Google sheets in a simple caching mechanism . |
41,354 | def _get_context_from_gdoc ( self , key ) : try : content = self . export_xlsx ( key ) data = process_xlsx ( content ) if 'values' in data : data = copy_global_values ( data ) return data except BadStatusLine : puts ( "Connection reset, reloading drive API" ) self . client = get_drive_api ( ) return self . _get_context... | Create a Jinja2 context from a Google spreadsheet . |
41,355 | def export_xlsx ( self , key ) : 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 ( downloa... | Download xlsx version of spreadsheet . |
41,356 | def generate_static_site ( self , output_root = None , extra_context = None ) : self . app . config [ 'BUILD_PATH' ] = output_root self . call_hook ( "generate" , self , output_root , extra_context ) if output_root is not None : self . app . config [ 'FREEZER_DESTINATION' ] = os . path . realpath ( output_root ) self .... | Bake out static site |
41,357 | def filter_files ( self , path ) : 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 ... | Exclude files based on blueprint and project configuration as well as hidden files . |
41,358 | def deploy_to_s3 ( self ) : 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 | Deploy a directory to an s3 bucket . |
41,359 | def s3_upload ( self , keyname , absolute_path ) : 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 = keyn... | Upload a file to s3 |
41,360 | def find_file_paths ( self ) : 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 : path = ( os . path . join ( rel_path , f ) , os . p... | A generator function that recursively finds all files in the upload directory . |
41,361 | def get_drive_api ( ) : 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 ) | Get drive API client based on settings . |
41,362 | def get_drive_api_from_file ( path ) : f = open ( path ) credentials = client . OAuth2Credentials . from_json ( f . read ( ) ) return _get_drive_api ( credentials ) | Open file with OAuth tokens . |
41,363 | def _get_drive_api ( credentials ) : http = httplib2 . Http ( ) http = credentials . authorize ( http ) service = discovery . build ( 'drive' , 'v2' , http = http ) service . credentials = credentials return service | For a given set of credentials return a drive API object . |
41,364 | def main ( ) : 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... | Primary Tarbell command dispatch . |
41,365 | def display_info ( args ) : 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 ( color... | Displays Tarbell info . |
41,366 | def tarbell_generate ( command , args , skip_args = False , extra_context = None , quiet = False ) : 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 ... | Generate static files . |
41,367 | def tarbell_install ( command , args ) : 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 tempdir = tempfile . mkdtemp ( ) try : testgit = sh ... | Install a project . |
41,368 | def tarbell_install_blueprint ( command , args ) : 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 ( ) ... | Install a project template . |
41,369 | def tarbell_list ( command , args ) : 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 ( pr... | List tarbell projects . |
41,370 | def tarbell_list_templates ( command , args ) : with ensure_settings ( command , args ) as settings : puts ( "\nAvailable project templates\n" ) _list_templates ( settings ) puts ( "" ) | List available Tarbell blueprints . |
41,371 | def tarbell_publish ( command , args ) : 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 configur... | Publish to s3 . |
41,372 | def tarbell_newproject ( command , args ) : with ensure_settings ( command , args ) as settings : name = _get_project_name ( args ) puts ( "Creating {0}" . format ( colored . cyan ( name ) ) ) path = _get_path ( name , settings ) _mkdir ( path ) try : _newproject ( command , path , name , settings ) except KeyboardInte... | Create new Tarbell project . |
41,373 | def tarbell_serve ( command , args ) : 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 . co... | Serve the current Tarbell project . |
41,374 | def tarbell_switch ( command , args ) : 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... | Switch to a project . |
41,375 | def tarbell_update ( command , args ) : 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 ) puts ( colored . yellow ( "Stashing local changes" ) ) puts ( git . stash ( ) ) puts... | Update the current tarbell project . |
41,376 | def tarbell_unpublish ( command , args ) : with ensure_settings ( command , args ) as settings , ensure_project ( command , args ) as site : show_error ( "Not implemented!" ) | Delete a project . |
41,377 | def tarbell_spreadsheet ( command , args ) : with ensure_settings ( command , args ) as settings , ensure_project ( command , args ) as site : try : spreadsheet_url = _google_spreadsheet_url ( site . project . SPREADSHEET_KEY ) except AttributeError : try : spreadsheet_url = _context_source_file_url ( site . project . ... | Open context spreadsheet |
41,378 | def _context_source_file_url ( path_or_url ) : if path_or_url . startswith ( 'http' ) : return path_or_url if path_or_url . startswith ( '/' ) : return "file://" + path_or_url return "file://" + os . path . join ( os . path . realpath ( os . getcwd ( ) ) , path_or_url ) | Returns a URL for a remote or local context CSV file |
41,379 | def _newproject ( command , path , name , settings ) : key = None title = _get_project_title ( ) template = _get_template ( settings ) git = sh . git . bake ( _cwd = path ) puts ( git . init ( ) ) if template . get ( "url" ) : puts ( git . submodule . add ( template [ 'url' ] , '_blueprint' ) ) puts ( git . submodule .... | Helper to create new project . |
41,380 | def _install_requirements ( path ) : 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 . ... | Install a blueprint s requirements . txt |
41,381 | def _get_project_name ( args ) : name = args . get ( 0 ) puts ( "" ) while not name : name = raw_input ( "What is the project's short directory name? (e.g. my_project) " ) return name | Get project name . |
41,382 | def _clean_suffix ( string , suffix ) : suffix_len = len ( suffix ) if len ( string ) < suffix_len : raise ValueError ( "A suffix can not be bigger than string argument." ) if string . endswith ( suffix ) : return string [ 0 : - suffix_len ] else : return string | If string endswith the suffix remove it . Else leave it alone . |
41,383 | def _get_path ( name , settings , mkdir = True ) : default_projects_path = settings . config . get ( "projects_path" ) path = None if default_projects_path : path = raw_input ( "\nWhere would you like to create this project? [{0}/{1}] " . format ( default_projects_path , name ) ) if not path : path = os . path . join (... | Generate a project path . |
41,384 | def _mkdir ( path ) : try : os . mkdir ( path ) except OSError as e : if e . errno == 17 : show_error ( "ABORTING: Directory {0} already exists." . format ( path ) ) else : show_error ( "ABORTING: OSError {0}" . format ( e ) ) sys . exit ( ) | Make a directory or bail . |
41,385 | def _get_template ( settings ) : puts ( "\nPick a template\n" ) template = None while not template : _list_templates ( settings ) index = raw_input ( "\nWhich template would you like to use? [1] " ) if not index : index = "1" try : index = int ( index ) - 1 return settings . config [ "project_templates" ] [ index ] exc... | Prompt user to pick template from a list . |
41,386 | def _list_templates ( settings ) : for idx , option in enumerate ( settings . config . get ( "project_templates" ) , start = 1 ) : puts ( " {0!s:5} {1!s:36}" . format ( colored . yellow ( "[{0}]" . format ( idx ) ) , colored . cyan ( option . get ( "name" ) ) ) ) if option . get ( "url" ) : puts ( " {0}\n" . form... | List templates from settings . |
41,387 | def _create_spreadsheet ( name , title , path , settings ) : if not settings . client_secrets : return None create = raw_input ( "Would you like to create a Google spreadsheet? [Y/n] " ) if create and not create . lower ( ) == "y" : return puts ( "Not creating spreadsheet." ) email_message = ( "What Google account(s) s... | Create Google spreadsheet . |
41,388 | def _add_user_to_file ( file_id , service , user_email , perm_type = 'user' , role = 'writer' ) : new_permission = { 'value' : user_email , 'type' : perm_type , 'role' : role } try : service . permissions ( ) . insert ( fileId = file_id , body = new_permission ) . execute ( ) except errors . HttpError as error : show_e... | Grants the given set of permissions for a given file_id . service is an already - credentialed Google Drive service instance . |
41,389 | def _copy_config_template ( name , title , template , path , key , settings ) : puts ( "\nCopying configuration file" ) context = settings . config context . update ( { "default_context" : { "name" : name , "title" : title , } , "name" : name , "title" : title , "template_repo_url" : template . get ( 'url' ) , "key" : ... | Get and render tarbell_config . py . template from Tarbell default . |
41,390 | def _delete_dir ( dir ) : try : shutil . rmtree ( dir ) except OSError as exc : if exc . errno != 2 : raise except UnboundLocalError : pass | Delete a directory . |
41,391 | def def_cmd ( name = None , short = None , fn = None , usage = None , help = None ) : command = Command ( name = name , short = short , fn = fn , usage = usage , help = help ) Command . register ( command ) | Define a command . |
41,392 | def save ( self ) : with open ( self . path , "w" ) as f : self . config [ "project_templates" ] = list ( filter ( lambda template : template . get ( "url" ) , self . config [ "project_templates" ] ) ) yaml . dump ( self . config , f , default_flow_style = False ) | Save settings . |
41,393 | def pprint_lines ( value ) : pformatted = pformat ( value , width = 1 , indent = 4 ) formatted = "{0}\n {1}\n{2}" . format ( pformatted [ 0 ] , pformatted [ 1 : - 1 ] , pformatted [ - 1 ] ) return Markup ( formatted ) | Pretty print lines |
41,394 | def plot_composition ( df , intervals , axes = None ) : generics = df . columns if ( axes is not None ) and ( len ( axes ) != len ( generics ) ) : raise ValueError ( "If 'axes' is not None then it must be the same " "length as 'df.columns'" ) if axes is None : _ , axes = plt . subplots ( nrows = len ( generics ) , ncol... | Plot time series of generics and label underlying instruments which these series are composed of . |
41,395 | def intervals ( weights ) : intrvls = [ ] if isinstance ( weights , dict ) : for root in weights : wts = weights [ root ] intrvls . append ( _intervals ( wts ) ) intrvls = pd . concat ( intrvls , axis = 0 ) else : intrvls = _intervals ( weights ) intrvls = intrvls . reset_index ( drop = True ) return intrvls | Extract intervals where generics are composed of different tradeable instruments . |
41,396 | def synchronize ( self ) : LOG . info ( _LI ( 'Syncing Neutron Router DB <-> EOS' ) ) routers , router_interfaces = self . get_routers_and_interfaces ( ) expected_vrfs = set ( ) if self . _use_vrf : expected_vrfs . update ( self . driver . _arista_router_name ( r [ 'id' ] , r [ 'name' ] ) for r in routers ) expected_vl... | Synchronizes Router DB from Neturon DB with EOS . |
41,397 | def create_router ( self , context , router ) : new_router = super ( AristaL3ServicePlugin , self ) . create_router ( context , router ) try : self . driver . create_router ( context , new_router ) return new_router except Exception : with excutils . save_and_reraise_exception ( ) : LOG . error ( _LE ( "Error creating ... | Create a new router entry in DB and create it Arista HW . |
41,398 | def update_router ( self , context , router_id , router ) : original_router = self . get_router ( context , router_id ) new_router = super ( AristaL3ServicePlugin , self ) . update_router ( context , router_id , router ) try : self . driver . update_router ( context , router_id , original_router , new_router ) return n... | Update an existing router in DB and update it in Arista HW . |
41,399 | def delete_router ( self , context , router_id ) : router = self . get_router ( context , router_id ) try : self . driver . delete_router ( context , router_id , router ) except Exception as e : LOG . error ( _LE ( "Error deleting router on Arista HW " "router %(r)s exception=%(e)s" ) , { 'r' : router , 'e' : e } ) sup... | Delete an existing router from Arista HW as well as from the DB . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.