idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
241,300
def build ( self , shutit ) : shutit_pexpect_session = ShutItPexpectSession ( shutit , 'target_child' , '/bin/bash' ) target_child = shutit_pexpect_session . pexpect_child shutit_pexpect_session . expect ( shutit_global . shutit_global_object . base_prompt . strip ( ) , timeout = 10 ) self . setup_host_child ( shutit )...
Sets up the machine ready for building .
241,301
def build ( self , shutit ) : if shutit . build [ 'delivery' ] in ( 'docker' , 'dockerfile' ) : if shutit . get_current_shutit_pexpect_session_environment ( ) . install_type == 'apt' : shutit . add_to_bashrc ( 'export DEBIAN_FRONTEND=noninteractive' ) if not shutit . command_available ( 'lsb_release' ) : shutit . insta...
Initializes target ready for build and updating package management if in container .
241,302
def __set_config ( self , cfg_section ) : defaults = [ 'shutit.core.alerting.emailer.mailto' , None , 'shutit.core.alerting.emailer.mailfrom' , 'angry@shutit.tk' , 'shutit.core.alerting.emailer.smtp_server' , 'localhost' , 'shutit.core.alerting.emailer.smtp_port' , 25 , 'shutit.core.alerting.emailer.use_tls' , True , '...
Set a local config array up according to defaults and main shutit configuration
241,303
def __get_smtp ( self ) : use_tls = self . config [ 'shutit.core.alerting.emailer.use_tls' ] if use_tls : smtp = SMTP ( self . config [ 'shutit.core.alerting.emailer.smtp_server' ] , self . config [ 'shutit.core.alerting.emailer.smtp_port' ] ) smtp . starttls ( ) else : smtp = SMTP_SSL ( self . config [ 'shutit.core.al...
Return the appropraite smtplib depending on wherther we re using TLS
241,304
def __compose ( self ) : msg = MIMEMultipart ( ) msg [ 'Subject' ] = self . config [ 'shutit.core.alerting.emailer.subject' ] msg [ 'To' ] = self . config [ 'shutit.core.alerting.emailer.mailto' ] msg [ 'From' ] = self . config [ 'shutit.core.alerting.emailer.mailfrom' ] if self . config [ 'shutit.core.alerting.emailer...
Compose the message pulling together body attachments etc
241,305
def send ( self , attachment_failure = False ) : if not self . config [ 'shutit.core.alerting.emailer.send_mail' ] : self . shutit . log ( 'emailer.send: Not configured to send mail!' , level = logging . INFO ) return True msg = self . __compose ( ) mailto = [ self . config [ 'shutit.core.alerting.emailer.mailto' ] ] s...
Send the email according to the configured setup
241,306
def setup_signals ( ) : signal . signal ( signal . SIGINT , shutit_util . ctrl_c_signal_handler ) signal . signal ( signal . SIGQUIT , shutit_util . ctrl_quit_signal_handler )
Set up the signal handlers .
241,307
def get_shutit_pexpect_sessions ( ) : sessions = [ ] for shutit_object in shutit_global_object . shutit_objects : for key in shutit_object . shutit_pexpect_sessions : sessions . append ( shutit_object . shutit_pexpect_sessions [ key ] ) return sessions
Returns all the shutit_pexpect sessions in existence .
241,308
def main ( ) : shutit = shutit_global . shutit_global_object . shutit_objects [ 0 ] if sys . version_info [ 0 ] == 2 : if sys . version_info [ 1 ] < 7 : shutit . fail ( 'Python version must be 2.7+' ) try : shutit . setup_shutit_obj ( ) except KeyboardInterrupt : shutit_util . print_debug ( sys . exc_info ( ) ) shutit_...
Main ShutIt function .
241,309
def has_blocking_background_send ( self ) : for background_object in self . background_objects : if background_object . block_other_commands and background_object . run_state in ( 'S' , 'N' ) : self . shutit_obj . log ( 'All objects are: ' + str ( self ) , level = logging . DEBUG ) self . shutit_obj . log ( 'The curren...
Check whether any blocking background commands are waiting to run . If any are return True . If none are return False .
241,310
def check_background_commands_complete ( self ) : unstarted_command_exists = False self . shutit_obj . log ( 'In check_background_commands_complete: all background objects: ' + str ( self . background_objects ) , level = logging . DEBUG ) self . shutit_obj . log ( 'Login id: ' + str ( self . login_id ) , level = loggin...
Check whether any background commands are running or to be run . If none are return True . If any are return False .
241,311
def open_remote ( cls , username , password , multifactor_password = None , client_id = None ) : blob = cls . fetch_blob ( username , password , multifactor_password , client_id ) return cls . open ( blob , username , password )
Fetches a blob from the server and creates a vault
241,312
def open ( cls , blob , username , password ) : return cls ( blob , blob . encryption_key ( username , password ) )
Creates a vault from a blob object
241,313
def fetch_blob ( cls , username , password , multifactor_password = None , client_id = None ) : session = fetcher . login ( username , password , multifactor_password , client_id ) blob = fetcher . fetch ( session ) fetcher . logout ( session ) return blob
Just fetches the blob could be used to store it locally
241,314
def extract_chunks ( blob ) : chunks = [ ] stream = BytesIO ( blob . bytes ) current_pos = stream . tell ( ) stream . seek ( 0 , 2 ) length = stream . tell ( ) stream . seek ( current_pos , 0 ) while stream . tell ( ) < length : chunks . append ( read_chunk ( stream ) ) return chunks
Splits the blob into chucks grouped by kind .
241,315
def parse_ACCT ( chunk , encryption_key ) : io = BytesIO ( chunk . payload ) id = read_item ( io ) name = decode_aes256_plain_auto ( read_item ( io ) , encryption_key ) group = decode_aes256_plain_auto ( read_item ( io ) , encryption_key ) url = decode_hex ( read_item ( io ) ) notes = decode_aes256_plain_auto ( read_it...
Parses an account chunk decrypts and creates an Account object . May return nil when the chunk does not represent an account . All secure notes are ACCTs but not all of them strore account information .
241,316
def parse_PRIK ( chunk , encryption_key ) : decrypted = decode_aes256 ( 'cbc' , encryption_key [ : 16 ] , decode_hex ( chunk . payload ) , encryption_key ) hex_key = re . match ( br'^LastPassPrivateKey<(?P<hex_key>.*)>LastPassPrivateKey$' , decrypted ) . group ( 'hex_key' ) rsa_key = RSA . importKey ( decode_hex ( hex_...
Parse PRIK chunk which contains private RSA key
241,317
def decode_aes256_cbc_base64 ( data , encryption_key ) : if not data : return b'' else : return decode_aes256 ( 'cbc' , decode_base64 ( data [ 1 : 25 ] ) , decode_base64 ( data [ 26 : ] ) , encryption_key )
Decrypts base64 encoded AES - 256 CBC bytes .
241,318
def api_delete ( service , file_id , owner_token ) : service += 'api/delete/%s' % file_id r = requests . post ( service , json = { 'owner_token' : owner_token , 'delete_token' : owner_token } ) r . raise_for_status ( ) if r . text == 'OK' : return True return False
Delete a file already uploaded to Send
241,319
def api_params ( service , file_id , owner_token , download_limit ) : service += 'api/params/%s' % file_id r = requests . post ( service , json = { 'owner_token' : owner_token , 'dlimit' : download_limit } ) r . raise_for_status ( ) if r . text == 'OK' : return True return False
Change the download limit for a file hosted on a Send Server
241,320
def api_download ( service , fileId , authorisation ) : data = tempfile . SpooledTemporaryFile ( max_size = SPOOL_SIZE , mode = 'w+b' ) headers = { 'Authorization' : 'send-v1 ' + unpadded_urlsafe_b64encode ( authorisation ) } url = service + 'api/download/' + fileId r = requests . get ( url , headers = headers , stream...
Given a Send url download and return the encrypted data and metadata
241,321
def decrypt_filedata ( data , keys ) : data . seek ( - 16 , 2 ) tag = data . read ( ) data . seek ( - 16 , 2 ) data . truncate ( ) data . seek ( 0 ) plain = tempfile . NamedTemporaryFile ( mode = 'w+b' , delete = False ) pbar = progbar ( fileSize ( data ) ) obj = Cryptodome . Cipher . AES . new ( keys . encryptKey , Cr...
Decrypts a file from Send
241,322
def sign_nonce ( key , nonce ) : return Cryptodome . Hash . HMAC . new ( key , nonce , digestmod = Cryptodome . Hash . SHA256 ) . digest ( )
sign the server nonce from the WWW - Authenticate header with an authKey
241,323
def api_password ( service , fileId , ownerToken , newAuthKey ) : service += 'api/password/%s' % fileId auth = sendclient . common . unpadded_urlsafe_b64encode ( newAuthKey ) r = requests . post ( service , json = { 'owner_token' : ownerToken , 'auth' : auth } ) r . raise_for_status ( ) if r . text == 'OK' : return Tru...
changes the authKey required to download a file hosted on a send server
241,324
def set_password ( url , ownerToken , password ) : service , fileId , key = sendclient . common . splitkeyurl ( url ) rawKey = sendclient . common . unpadded_urlsafe_b64decode ( key ) keys = sendclient . common . secretKeys ( rawKey , password , url ) return api_password ( service , fileId , ownerToken , keys . newAuth...
set or change the password required to download a file hosted on a send server .
241,325
def splitkeyurl ( url ) : key = url [ - 22 : ] urlid = url [ - 34 : - 24 ] service = url [ : - 43 ] return service , urlid , key
Splits a Send url into key urlid and prefix for the Send server Should handle any hostname but will brake on key & id length changes
241,326
def api_upload ( service , encData , encMeta , keys ) : service += 'api/upload' files = requests_toolbelt . MultipartEncoder ( fields = { 'file' : ( 'blob' , encData , 'application/octet-stream' ) } ) pbar = progbar ( files . len ) monitor = requests_toolbelt . MultipartEncoderMonitor ( files , lambda files : pbar . up...
Uploads data to Send . Caution! Data is uploaded as given this function will not encrypt it for you
241,327
def send_file ( service , file , fileName = None , password = None , ignoreVersion = False ) : if checkServerVersion ( service , ignoreVersion = ignoreVersion ) == False : print ( '\033[1;41m!!! Potentially incompatible server version !!!\033[0m' ) fileName = fileName if fileName != None else os . path . basename ( fil...
Encrypt & Upload a file to send and return the download URL
241,328
def fetch ( self , endpoint , data = None ) : payload = { "lastServerChangeId" : "-1" , "csrf" : self . __csrf , "apiClient" : "WEB" } if data is not None : payload . update ( data ) return self . post ( endpoint , payload )
for getting data after logged in
241,329
def __identify_user ( self , username , csrf ) : data = { "username" : username , "csrf" : csrf , "apiClient" : "WEB" , "bindDevice" : "false" , "skipLinkAccount" : "false" , "redirectTo" : "" , "skipFirstUse" : "" , "referrerId" : "" , } r = self . post ( "/login/identifyUser" , data ) if r . status_code == requests ....
Returns reusable CSRF code and the auth level as a 2 - tuple
241,330
def get_args ( cls , dist , header = None ) : if header is None : header = cls . get_header ( ) spec = str ( dist . as_requirement ( ) ) for type_ in 'console' , 'gui' : group = type_ + '_scripts' for name , ep in dist . get_entry_map ( group ) . items ( ) : if re . search ( r'[\\/]' , name ) : raise ValueError ( "Path...
Overrides easy_install . ScriptWriter . get_args
241,331
def clean_pip_env ( ) -> Generator [ None , None , None ] : require_venv = os . environ . pop ( PIP_REQUIRE_VIRTUALENV , None ) try : yield finally : if require_venv is not None : os . environ [ PIP_REQUIRE_VIRTUALENV ] = require_venv
A context manager for temporarily removing PIP_REQUIRE_VIRTUALENV from the environment .
241,332
def install ( args : List [ str ] ) -> None : with clean_pip_env ( ) : subprocess_env = os . environ . copy ( ) sitedir_index = _first_sitedir_index ( ) _extend_python_path ( subprocess_env , sys . path [ sitedir_index : ] ) process = subprocess . Popen ( [ sys . executable , "-m" , "pip" , "--disable-pip-version-check...
pip install as a function .
241,333
def current_zipfile ( ) : if zipfile . is_zipfile ( sys . argv [ 0 ] ) : fd = open ( sys . argv [ 0 ] , "rb" ) return zipfile . ZipFile ( fd )
A function to vend the current zipfile if any
241,334
def extract_site_packages ( archive , target_path , compile_pyc , compile_workers = 0 , force = False ) : parent = target_path . parent target_path_tmp = Path ( parent , target_path . stem + ".tmp" ) lock = Path ( parent , target_path . stem + ".lock" ) if not parent . exists ( ) : parent . mkdir ( parents = True , exi...
Extract everything in site - packages to a specified path .
241,335
def bootstrap ( ) : archive = current_zipfile ( ) env = Environment . from_json ( archive . read ( "environment.json" ) . decode ( ) ) site_packages = cache_path ( archive , env . root , env . build_id ) / "site-packages" if not site_packages . exists ( ) or env . force_extract : extract_site_packages ( archive , site_...
Actually bootstrap our shiv environment .
241,336
def write_file_prefix ( f : IO [ Any ] , interpreter : str ) -> None : if len ( interpreter ) > BINPRM_BUF_SIZE : sys . exit ( BINPRM_ERROR ) f . write ( b"#!" + interpreter . encode ( sys . getfilesystemencoding ( ) ) + b"\n" )
Write a shebang line .
241,337
def create_archive ( source : Path , target : Path , interpreter : str , main : str , compressed : bool = True ) -> None : mod , sep , fn = main . partition ( ":" ) mod_ok = all ( part . isidentifier ( ) for part in mod . split ( "." ) ) fn_ok = all ( part . isidentifier ( ) for part in fn . split ( "." ) ) if not ( se...
Create an application archive from SOURCE .
241,338
def acquire_win ( lock_file ) : try : fd = os . open ( lock_file , OPEN_MODE ) except OSError : pass else : try : msvcrt . locking ( fd , msvcrt . LK_NBLCK , 1 ) except ( IOError , OSError ) : os . close ( fd ) else : return fd
Acquire a lock file on windows .
241,339
def acquire_nix ( lock_file ) : fd = os . open ( lock_file , OPEN_MODE ) try : fcntl . flock ( fd , fcntl . LOCK_EX | fcntl . LOCK_NB ) except ( IOError , OSError ) : os . close ( fd ) else : return fd
Acquire a lock file on linux or osx .
241,340
def find_entry_point ( site_packages : Path , console_script : str ) -> str : config_parser = ConfigParser ( ) config_parser . read ( site_packages . rglob ( "entry_points.txt" ) ) return config_parser [ "console_scripts" ] [ console_script ]
Find a console_script in a site - packages directory .
241,341
def copy_bootstrap ( bootstrap_target : Path ) -> None : for bootstrap_file in importlib_resources . contents ( bootstrap ) : if importlib_resources . is_resource ( bootstrap , bootstrap_file ) : with importlib_resources . path ( bootstrap , bootstrap_file ) as f : shutil . copyfile ( f . absolute ( ) , bootstrap_targe...
Copy bootstrap code from shiv into the pyz .
241,342
def _interpreter_path ( append_version : bool = False ) -> str : base_dir = Path ( getattr ( sys , "real_prefix" , sys . base_prefix ) ) . resolve ( ) sys_exec = Path ( sys . executable ) name = sys_exec . stem suffix = sys_exec . suffix if append_version : name += str ( sys . version_info . major ) name += suffix try ...
A function to return the path to the current Python interpreter .
241,343
def main ( output_file : str , entry_point : Optional [ str ] , console_script : Optional [ str ] , python : Optional [ str ] , site_packages : Optional [ str ] , compressed : bool , compile_pyc : bool , extend_pythonpath : bool , pip_args : List [ str ] , ) -> None : if not pip_args and not site_packages : sys . exit ...
Shiv is a command line utility for building fully self - contained Python zipapps as outlined in PEP 441 but with all their dependencies included!
241,344
def get_session ( * , env_vars = None , loop = None ) : loop = loop or asyncio . get_event_loop ( ) return AioSession ( session_vars = env_vars , loop = loop )
Return a new session object .
241,345
async def read ( self , amt = None ) : chunk = await self . __wrapped__ . read ( amt if amt is not None else - 1 ) self . _self_amount_read += len ( chunk ) if amt is None or ( not chunk and amt > 0 ) : self . _verify_content_length ( ) return chunk
Read at most amt bytes from the stream .
241,346
async def iter_lines ( self , chunk_size = 1024 ) : pending = b'' async for chunk in self . iter_chunks ( chunk_size ) : lines = ( pending + chunk ) . splitlines ( True ) for line in lines [ : - 1 ] : await yield_ ( line . splitlines ( ) [ 0 ] ) pending = lines [ - 1 ] if pending : await yield_ ( pending . splitlines (...
Return an iterator to yield lines from the raw stream .
241,347
async def iter_chunks ( self , chunk_size = _DEFAULT_CHUNK_SIZE ) : while True : current_chunk = await self . read ( chunk_size ) if current_chunk == b"" : break await yield_ ( current_chunk )
Return an iterator to yield chunks of chunk_size bytes from the raw stream .
241,348
def get_items ( start_num , num_items ) : result = [ ] for i in range ( start_num , start_num + num_items ) : result . append ( { 'pk' : { 'S' : 'item{0}' . format ( i ) } } ) return result
Generate a sequence of dynamo items
241,349
def create_batch_write_structure ( table_name , start_num , num_items ) : return { table_name : [ { 'PutRequest' : { 'Item' : item } } for item in get_items ( start_num , num_items ) ] }
Create item structure for passing to batch_write_item
241,350
def get_paginator ( self , operation_name ) : if not self . can_paginate ( operation_name ) : raise OperationNotPageableError ( operation_name = operation_name ) else : Paginator . PAGE_ITERATOR_CLS = AioPageIterator actual_operation_name = self . _PY_TO_OP_NAME [ operation_name ] def paginate ( self , ** kwargs ) : re...
Create a paginator for an operation .
241,351
def get_waiter ( self , waiter_name ) : config = self . _get_waiter_config ( ) if not config : raise ValueError ( "Waiter does not exist: %s" % waiter_name ) model = waiter . WaiterModel ( config ) mapping = { } for name in model . waiter_names : mapping [ xform_name ( name ) ] = name if waiter_name not in mapping : ra...
Returns an object that can wait for some condition .
241,352
def url_fix ( s , charset = None ) : if charset : warnings . warn ( "{}.url_fix() charset argument is deprecated" . format ( __name__ ) , DeprecationWarning ) scheme , netloc , path , querystring , fragment = urlsplit ( s ) path = quote ( path , b'/%' ) querystring = quote_plus ( querystring , b':&=' ) return urlunspli...
escapes special characters
241,353
def httprettified ( test = None , allow_net_connect = True ) : def decorate_unittest_TestCase_setUp ( klass ) : use_addCleanup = hasattr ( klass , 'addCleanup' ) original_setUp = ( klass . setUp if hasattr ( klass , 'setUp' ) else None ) def new_setUp ( self ) : httpretty . reset ( ) httpretty . enable ( allow_net_conn...
decorator for test functions
241,354
def parse_request_body ( self , body ) : PARSING_FUNCTIONS = { 'application/json' : json . loads , 'text/json' : json . loads , 'application/x-www-form-urlencoded' : self . parse_querystring , } content_type = self . headers . get ( 'content-type' , '' ) do_parse = PARSING_FUNCTIONS . get ( content_type , FALLBACK_FUNC...
Attempt to parse the post based on the content - type passed . Return the regular body if not
241,355
def fill_filekind ( self , fk ) : now = datetime . utcnow ( ) headers = { 'status' : self . status , 'date' : now . strftime ( '%a, %d %b %Y %H:%M:%S GMT' ) , 'server' : 'Python/HTTPretty' , 'connection' : 'close' , } if self . forcing_headers : headers = self . forcing_headers if self . adding_headers : headers . upda...
writes HTTP Response data to a file descriptor
241,356
def draw_text ( stdscr , text , color = 0 , fallback = None , title = None ) : if fallback is None : fallback = text y , x = stdscr . getmaxyx ( ) if title : title = pad_to_size ( title , x , 1 ) if "\n" in title . rstrip ( "\n" ) : title += "\n" * 5 text = title + "\n" + pad_to_size ( text , x , len ( text . split ( "...
Draws text in the given color . Duh .
241,357
def format_seconds ( seconds , hide_seconds = False ) : if seconds <= 60 : return str ( seconds ) output = "" for period , period_seconds in ( ( 'y' , 31557600 ) , ( 'd' , 86400 ) , ( 'h' , 3600 ) , ( 'm' , 60 ) , ( 's' , 1 ) , ) : if seconds >= period_seconds and not ( hide_seconds and period == 's' ) : output += str ...
Returns a human - readable string representation of the given amount of seconds .
241,358
def graceful_ctrlc ( func ) : @ wraps ( func ) def wrapper ( * args , ** kwargs ) : try : return func ( * args , ** kwargs ) except KeyboardInterrupt : exit ( 1 ) return wrapper
Makes the decorated function exit with code 1 on CTRL + C .
241,359
def pad_to_size ( text , x , y ) : input_lines = text . rstrip ( ) . split ( "\n" ) longest_input_line = max ( map ( len , input_lines ) ) number_of_input_lines = len ( input_lines ) x = max ( x , longest_input_line ) y = max ( y , number_of_input_lines ) output = "" padding_top = int ( ( y - number_of_input_lines ) / ...
Adds whitespace to text to center it within a frame of the given dimensions .
241,360
def parse_timestr ( timestr ) : timedelta_secs = parse_timedelta ( timestr ) sync_start = datetime . now ( ) if timedelta_secs : target = datetime . now ( ) + timedelta ( seconds = timedelta_secs ) elif timestr . isdigit ( ) : target = datetime . now ( ) + timedelta ( seconds = int ( timestr ) ) else : try : target = p...
Parse a string describing a point in time .
241,361
def parse_timedelta ( deltastr ) : matches = TIMEDELTA_REGEX . match ( deltastr ) if not matches : return None components = { } for name , value in matches . groupdict ( ) . items ( ) : if value : components [ name ] = int ( value ) for period , hours in ( ( 'days' , 24 ) , ( 'years' , 8766 ) ) : if period in component...
Parse a string describing a period of time .
241,362
def _verify_signature ( self , message , signature ) : if self . negotiate_flags & NegotiateFlags . NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY : actual_checksum = signature [ 4 : 12 ] actual_seq_num = struct . unpack ( "<I" , signature [ 12 : 16 ] ) [ 0 ] else : actual_checksum = signature [ 8 : 12 ] actual_seq_num = s...
Will verify that the signature received from the server matches up with the expected signature computed locally . Will throw an exception if they do not match
241,363
def regex_opt_inner ( strings , open_paren ) : close_paren = open_paren and ')' or '' if not strings : return '' first = strings [ 0 ] if len ( strings ) == 1 : return open_paren + escape ( first ) + close_paren if not first : return open_paren + regex_opt_inner ( strings [ 1 : ] , '(?:' ) + '?' + close_paren if len ( ...
Return a regex that matches any string in the sorted list of strings .
241,364
def regex_opt ( strings , prefix = '' , suffix = '' ) : strings = sorted ( strings ) return prefix + regex_opt_inner ( strings , '(' ) + suffix
Return a compiled regex that matches any string in the given list .
241,365
def open_resource ( name ) : name_parts = name . lstrip ( '/' ) . split ( '/' ) for part in name_parts : if part == os . path . pardir or os . path . sep in part : raise ValueError ( 'Bad path segment: %r' % part ) filename = os . path . join ( os . path . dirname ( __file__ ) , 'zoneinfo' , * name_parts ) if not os . ...
Open a resource from the zoneinfo subdir for reading .
241,366
def FixedOffset ( offset , _tzinfos = { } ) : if offset == 0 : return UTC info = _tzinfos . get ( offset ) if info is None : info = _tzinfos . setdefault ( offset , _FixedOffset ( offset ) ) return info
return a fixed - offset timezone based off a number of minutes .
241,367
def boolean_or_list ( config_name , args , configs , alternative_names = [ ] ) : for key in alternative_names + [ config_name ] : if hasattr ( args , key ) and getattr ( args , key ) : setattr ( args , config_name , [ '.*' ] ) return setattr ( args , config_name , [ ] ) option = None alternative_names . insert ( 0 , co...
Get a boolean or list of regexes from args and configs .
241,368
def get_style_defs ( self , arg = '' ) : cp = self . commandprefix styles = [ ] for name , definition in iteritems ( self . cmd2def ) : styles . append ( r'\expandafter\def\csname %s@tok@%s\endcsname{%s}' % ( cp , name , definition ) ) return STYLE_TEMPLATE % { 'cp' : self . commandprefix , 'styles' : '\n' . join ( sty...
Return the command sequences needed to define the commands used to format text in the verbatim environment . arg is ignored .
241,369
def _fn_matches ( fn , glob ) : if glob not in _pattern_cache : pattern = _pattern_cache [ glob ] = re . compile ( fnmatch . translate ( glob ) ) return pattern . match ( fn ) return _pattern_cache [ glob ] . match ( fn )
Return whether the supplied file name fn matches pattern filename .
241,370
def get_all_formatters ( ) : for info in itervalues ( FORMATTERS ) : if info [ 1 ] not in _formatter_cache : _load_formatters ( info [ 0 ] ) yield _formatter_cache [ info [ 1 ] ] for _ , formatter in find_plugin_formatters ( ) : yield formatter
Return a generator for all formatter classes .
241,371
def find_formatter_class ( alias ) : for module_name , name , aliases , _ , _ in itervalues ( FORMATTERS ) : if alias in aliases : if name not in _formatter_cache : _load_formatters ( module_name ) return _formatter_cache [ name ] for _ , cls in find_plugin_formatters ( ) : if alias in cls . aliases : return cls
Lookup a formatter by alias .
241,372
def get_formatter_by_name ( _alias , ** options ) : cls = find_formatter_class ( _alias ) if cls is None : raise ClassNotFound ( "no formatter found for name %r" % _alias ) return cls ( ** options )
Lookup and instantiate a formatter by alias .
241,373
def load_formatter_from_file ( filename , formattername = "CustomFormatter" , ** options ) : try : custom_namespace = { } exec ( open ( filename , 'rb' ) . read ( ) , custom_namespace ) if formattername not in custom_namespace : raise ClassNotFound ( 'no valid %s class found in %s' % ( formattername , filename ) ) form...
Load a formatter from a file .
241,374
def get_formatter_for_filename ( fn , ** options ) : fn = basename ( fn ) for modname , name , _ , filenames , _ in itervalues ( FORMATTERS ) : for filename in filenames : if _fn_matches ( fn , filename ) : if name not in _formatter_cache : _load_formatters ( modname ) return _formatter_cache [ name ] ( ** options ) fo...
Lookup and instantiate a formatter by filename pattern .
241,375
def get_tokens_unprocessed ( self , text , stack = ( 'root' , ) ) : self . content_type = None return RegexLexer . get_tokens_unprocessed ( self , text , stack )
Reset the content - type state .
241,376
def find_lexer_class ( name ) : if name in _lexer_cache : return _lexer_cache [ name ] for module_name , lname , aliases , _ , _ in itervalues ( LEXERS ) : if name == lname : _load_lexers ( module_name ) return _lexer_cache [ name ] for cls in find_plugin_lexers ( ) : if cls . name == name : return cls
Lookup a lexer class by name .
241,377
def find_lexer_class_by_name ( _alias ) : if not _alias : raise ClassNotFound ( 'no lexer for alias %r found' % _alias ) for module_name , name , aliases , _ , _ in itervalues ( LEXERS ) : if _alias . lower ( ) in aliases : if name not in _lexer_cache : _load_lexers ( module_name ) return _lexer_cache [ name ] for cls ...
Lookup a lexer class by alias .
241,378
def load_lexer_from_file ( filename , lexername = "CustomLexer" , ** options ) : try : custom_namespace = { } exec ( open ( filename , 'rb' ) . read ( ) , custom_namespace ) if lexername not in custom_namespace : raise ClassNotFound ( 'no valid %s class found in %s' % ( lexername , filename ) ) lexer_class = custom_nam...
Load a lexer from a file .
241,379
def get_lexer_for_mimetype ( _mime , ** options ) : for modname , name , _ , _ , mimetypes in itervalues ( LEXERS ) : if _mime in mimetypes : if name not in _lexer_cache : _load_lexers ( modname ) return _lexer_cache [ name ] ( ** options ) for cls in find_plugin_lexers ( ) : if _mime in cls . mimetypes : return cls ( ...
Get a lexer for a mimetype .
241,380
def _iter_lexerclasses ( plugins = True ) : for key in sorted ( LEXERS ) : module_name , name = LEXERS [ key ] [ : 2 ] if name not in _lexer_cache : _load_lexers ( module_name ) yield _lexer_cache [ name ] if plugins : for lexer in find_plugin_lexers ( ) : yield lexer
Return an iterator over all lexer classes .
241,381
def get_file_stats ( file_name , entity_type = 'file' , lineno = None , cursorpos = None , plugin = None , language = None , local_file = None ) : language = standardize_language ( language , plugin ) stats = { 'language' : language , 'dependencies' : [ ] , 'lines' : None , 'lineno' : lineno , 'cursorpos' : cursorpos ,...
Returns a hash of information about the entity .
241,382
def guess_language ( file_name , local_file ) : lexer = None language = get_language_from_extension ( file_name ) if language : lexer = get_lexer ( language ) else : lexer = smart_guess_lexer ( file_name , local_file ) if lexer : language = u ( lexer . name ) return language , lexer
Guess lexer and language for a file .
241,383
def smart_guess_lexer ( file_name , local_file ) : lexer = None text = get_file_head ( file_name ) lexer1 , accuracy1 = guess_lexer_using_filename ( local_file or file_name , text ) lexer2 , accuracy2 = guess_lexer_using_modeline ( text ) if lexer1 : lexer = lexer1 if ( lexer2 and accuracy2 and ( not accuracy1 or accur...
Guess Pygments lexer for a file .
241,384
def guess_lexer_using_filename ( file_name , text ) : lexer , accuracy = None , None try : lexer = custom_pygments_guess_lexer_for_filename ( file_name , text ) except SkipHeartbeat as ex : raise SkipHeartbeat ( u ( ex ) ) except : log . traceback ( logging . DEBUG ) if lexer is not None : try : accuracy = lexer . anal...
Guess lexer for given text limited to lexers for this file s extension .
241,385
def guess_lexer_using_modeline ( text ) : lexer , accuracy = None , None file_type = None try : file_type = get_filetype_from_buffer ( text ) except : log . traceback ( logging . DEBUG ) if file_type is not None : try : lexer = get_lexer_by_name ( file_type ) except ClassNotFound : log . traceback ( logging . DEBUG ) i...
Guess lexer for given text using Vim modeline .
241,386
def get_language_from_extension ( file_name ) : filepart , extension = os . path . splitext ( file_name ) pathpart , filename = os . path . split ( file_name ) if filename == 'go.mod' : return 'Go' if re . match ( r'\.h.*$' , extension , re . IGNORECASE ) or re . match ( r'\.c.*$' , extension , re . IGNORECASE ) : if o...
Returns a matching language for the given file extension .
241,387
def standardize_language ( language , plugin ) : if not language : return None if plugin : plugin = plugin . split ( ' ' ) [ - 1 ] . split ( '/' ) [ 0 ] . split ( '-' ) [ 0 ] standardized = get_language_from_json ( language , plugin ) if standardized is not None : return standardized return get_language_from_json ( lan...
Maps a string to the equivalent Pygments language .
241,388
def get_language_from_json ( language , key ) : file_name = os . path . join ( os . path . dirname ( __file__ ) , 'languages' , '{0}.json' ) . format ( key . lower ( ) ) if os . path . exists ( file_name ) : try : with open ( file_name , 'r' , encoding = 'utf-8' ) as fh : languages = json . loads ( fh . read ( ) ) if l...
Finds the given language in a json file .
241,389
def get_file_head ( file_name ) : text = None try : with open ( file_name , 'r' , encoding = 'utf-8' ) as fh : text = fh . read ( 512000 ) except : try : with open ( file_name , 'r' , encoding = sys . getfilesystemencoding ( ) ) as fh : text = fh . read ( 512000 ) except : log . traceback ( logging . DEBUG ) return tex...
Returns the first 512000 bytes of the file s contents .
241,390
def custom_pygments_guess_lexer_for_filename ( _fn , _text , ** options ) : fn = basename ( _fn ) primary = { } matching_lexers = set ( ) for lexer in _iter_lexerclasses ( ) : for filename in lexer . filenames : if _fn_matches ( fn , filename ) : matching_lexers . add ( lexer ) primary [ lexer ] = True for filename in ...
Overwrite pygments . lexers . guess_lexer_for_filename to customize the priority of different lexers based on popularity of languages .
241,391
def customize_lexer_priority ( file_name , accuracy , lexer ) : priority = lexer . priority lexer_name = lexer . name . lower ( ) . replace ( 'sharp' , '#' ) if lexer_name in LANGUAGES : priority = LANGUAGES [ lexer_name ] elif lexer_name == 'matlab' : available_extensions = extensions_in_same_folder ( file_name ) if '...
Customize lexer priority
241,392
def extensions_in_same_folder ( file_name ) : directory = os . path . dirname ( file_name ) files = os . listdir ( directory ) extensions = list ( zip ( * map ( os . path . splitext , files ) ) ) [ 1 ] extensions = set ( [ ext . lower ( ) for ext in extensions ] ) return extensions
Returns a list of file extensions from the same folder as file_name .
241,393
def analyse_text ( text ) : if re . search ( r'/\*\**\s*rexx' , text , re . IGNORECASE ) : return 1.0 elif text . startswith ( '/*' ) : lowerText = text . lower ( ) result = sum ( weight for ( pattern , weight ) in RexxLexer . PATTERNS_AND_WEIGHTS if pattern . search ( lowerText ) ) + 0.01 return min ( result , 1.0 )
Check for inital comment and patterns that distinguish Rexx from other C - like languages .
241,394
def analyse_text ( text ) : result = 0.0 lines = text . split ( '\n' ) hasEndProc = False hasHeaderComment = False hasFile = False hasJob = False hasProc = False hasParm = False hasReport = False def isCommentLine ( line ) : return EasytrieveLexer . _COMMENT_LINE_REGEX . match ( lines [ 0 ] ) is not None def isEmptyLin...
Perform a structural analysis for basic Easytrieve constructs .
241,395
def analyse_text ( text ) : result = 0.0 lines = text . split ( '\n' ) if len ( lines ) > 0 : if JclLexer . _JOB_HEADER_PATTERN . match ( lines [ 0 ] ) : result = 1.0 assert 0.0 <= result <= 1.0 return result
Recognize JCL job by header .
241,396
def _objdump_lexer_tokens ( asm_lexer ) : hex_re = r'[0-9A-Za-z]' return { 'root' : [ ( '(.*?)(:)( +file format )(.*?)$' , bygroups ( Name . Label , Punctuation , Text , String ) ) , ( '(Disassembly of section )(.*?)(:)$' , bygroups ( Text , Name . Label , Punctuation ) ) , ( '(' + hex_re + '+)( )(<)(.*?)([-+])(0[xX][A...
Common objdump lexer tokens to wrap an ASM lexer .
241,397
def get_key ( self , fileobj ) : mapping = self . get_map ( ) if mapping is None : raise RuntimeError ( "Selector is closed" ) try : return mapping [ fileobj ] except KeyError : raise KeyError ( "{0!r} is not registered" . format ( fileobj ) )
Return the key associated with a registered file object .
241,398
def get_filetype_from_buffer ( buf , max_lines = 5 ) : lines = buf . splitlines ( ) for l in lines [ - 1 : - max_lines - 1 : - 1 ] : ret = get_filetype_from_line ( l ) if ret : return ret for i in range ( max_lines , - 1 , - 1 ) : if i < len ( lines ) : ret = get_filetype_from_line ( lines [ i ] ) if ret : return ret r...
Scan the buffer for modelines and return filetype if one is found .
241,399
def get_font ( self , bold , oblique ) : if bold and oblique : return self . fonts [ 'BOLDITALIC' ] elif bold : return self . fonts [ 'BOLD' ] elif oblique : return self . fonts [ 'ITALIC' ] else : return self . fonts [ 'NORMAL' ]
Get the font based on bold and italic flags .