idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
52,400 | def build_report ( self , msg = '' ) : shutit_global . shutit_global_object . yield_to_draw ( ) s = '\n' s += '################################################################################\n' s += '# COMMAND HISTORY BEGIN ' + shutit_global . shutit_global_object . build_id + '\n' s += self . get_commands ( ) s += '#... | Resposible for constructing a report to be output as part of the build . Returns report as a string . |
52,401 | def match_string ( self , string_to_match , regexp ) : shutit_global . shutit_global_object . yield_to_draw ( ) if not isinstance ( string_to_match , str ) : return None lines = string_to_match . split ( '\r\n' ) new_lines = [ ] for line in lines : new_lines = new_lines + line . split ( '\r' ) for line in lines : new_l... | Get regular expression from the first of the lines passed in in string that matched . Handles first group of regexp as a return value . |
52,402 | def is_to_be_built_or_is_installed ( self , shutit_module_obj ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfg = self . cfg if cfg [ shutit_module_obj . module_id ] [ 'shutit.core.module.build' ] : return True return self . is_installed ( shutit_module_obj ) | Returns true if this module is configured to be built or if it is already installed . |
52,403 | def is_installed ( self , shutit_module_obj ) : shutit_global . shutit_global_object . yield_to_draw ( ) if shutit_module_obj . module_id in self . get_current_shutit_pexpect_session_environment ( ) . modules_installed : return True if shutit_module_obj . module_id in self . get_current_shutit_pexpect_session_environme... | Returns true if this module is installed . Uses cache where possible . |
52,404 | def allowed_image ( self , module_id ) : shutit_global . shutit_global_object . yield_to_draw ( ) self . log ( "In allowed_image: " + module_id , level = logging . DEBUG ) cfg = self . cfg if self . build [ 'ignoreimage' ] : self . log ( "ignoreimage == true, returning true" + module_id , level = logging . DEBUG ) retu... | Given a module id determine whether the image is allowed to be built . |
52,405 | def print_modules ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfg = self . cfg module_string = '' module_string += 'Modules: \n' module_string += ' Run order Build Remove Module ID\n' for module_id in self . module_ids ( ) : module_string += ' ' + str ( self . shutit_map [ module_... | Returns a string table representing the modules in the ShutIt module map . |
52,406 | def load_shutit_modules ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) if self . loglevel <= logging . DEBUG : self . log ( 'ShutIt module paths now: ' , level = logging . DEBUG ) self . log ( self . host [ 'shutit_module_path' ] , level = logging . DEBUG ) for shutit_module_path in self . host [ '... | Responsible for loading the shutit modules based on the configured module paths . |
52,407 | def get_command ( self , command ) : shutit_global . shutit_global_object . yield_to_draw ( ) if command in ( 'md5sum' , 'sed' , 'head' ) : if self . get_current_shutit_pexpect_session_environment ( ) . distro == 'osx' : return 'g' + command return command | Helper function for osx - return gnu utils rather than default for eg head and md5sum where possible and needed . |
52,408 | def get_send_command ( self , send ) : shutit_global . shutit_global_object . yield_to_draw ( ) if send is None : return send cmd_arr = send . split ( ) if cmd_arr and cmd_arr [ 0 ] in ( 'md5sum' , 'sed' , 'head' ) : newcmd = self . get_command ( cmd_arr [ 0 ] ) send = send . replace ( cmd_arr [ 0 ] , newcmd ) return s... | Internal helper function to get command that s really sent |
52,409 | def load_configs ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) configs = [ ( 'defaults' , StringIO ( default_cnf ) ) , os . path . expanduser ( '~/.shutit/config' ) , os . path . join ( self . host [ 'shutit_path' ] , 'config' ) , 'configs/build.cnf' ] for config_file_name in self . build [ 'extra... | Responsible for loading config files into ShutIt . Recurses down from configured shutit module paths . |
52,410 | def config_collection ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) self . log ( 'In config_collection' , level = logging . DEBUG ) cfg = self . cfg for module_id in self . module_ids ( ) : self . get_config ( module_id , 'shutit.core.module.build' , None , boolean = True , forcenone = True ) self... | Collect core config from config files for all seen modules . |
52,411 | def print_config ( self , cfg , hide_password = True , history = False , module_id = None ) : shutit_global . shutit_global_object . yield_to_draw ( ) cp = self . config_parser s = '' keys1 = list ( cfg . keys ( ) ) if keys1 : keys1 . sort ( ) for k in keys1 : if module_id is not None and k != module_id : continue if i... | Returns a string representing the config of this ShutIt run . |
52,412 | def process_args ( self , args ) : shutit_global . shutit_global_object . yield_to_draw ( ) assert isinstance ( args , ShutItInit ) , shutit_util . print_debug ( ) if args . action == 'version' : shutit_global . shutit_global_object . shutit_print ( 'ShutIt version: ' + shutit . shutit_version ) shutit_global . shutit_... | Process the args we have . args is always a ShutItInit object . |
52,413 | def check_deps ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfg = self . cfg self . log ( 'PHASE: dependencies' , level = logging . DEBUG ) self . pause_point ( '\nNow checking for dependencies between modules' , print_input = False , level = 3 ) to_build = [ self . shutit_map [ module_id ] for m... | Dependency checking phase is performed in this method . |
52,414 | def check_conflicts ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfg = self . cfg self . log ( 'PHASE: conflicts' , level = logging . DEBUG ) errs = [ ] self . pause_point ( '\nNow checking for conflicts between modules' , print_input = False , level = 3 ) for module_id in self . module_ids ( ) :... | Checks for any conflicts between modules configured to be built . |
52,415 | def do_remove ( self , loglevel = logging . DEBUG ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfg = self . cfg self . log ( 'PHASE: remove' , level = loglevel ) self . pause_point ( '\nNow removing any modules that need removing' , print_input = False , level = 3 ) for module_id in self . module_ids ( ... | Remove modules by calling remove method on those configured for removal . |
52,416 | def do_build ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfg = self . cfg self . log ( 'PHASE: build, repository work' , level = logging . DEBUG ) module_id_list = self . module_ids ( ) if self . build [ 'deps_only' ] : module_id_list_build_only = filter ( lambda x : cfg [ x ] [ 'shutit.core.mod... | Runs build phase building any modules that we ve determined need building . |
52,417 | def stop_all ( self , run_order = - 1 ) : shutit_global . shutit_global_object . yield_to_draw ( ) for module_id in self . module_ids ( rev = True ) : shutit_module_obj = self . shutit_map [ module_id ] if run_order == - 1 or shutit_module_obj . run_order <= run_order : if self . is_installed ( shutit_module_obj ) : if... | Runs stop method on all modules less than the passed - in run_order . Used when target is exporting itself mid - build so we clean up state before committing run files etc . |
52,418 | def start_all ( self , run_order = - 1 ) : shutit_global . shutit_global_object . yield_to_draw ( ) for module_id in self . module_ids ( ) : shutit_module_obj = self . shutit_map [ module_id ] if run_order == - 1 or shutit_module_obj . run_order <= run_order : if self . is_installed ( shutit_module_obj ) : if not shuti... | Runs start method on all modules less than the passed - in run_order . Used when target is exporting itself mid - build so we can export a clean target and still depended - on modules running if necessary . |
52,419 | def init_shutit_map ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) modules = self . shutit_modules if len ( [ mod for mod in modules if mod . run_order > 0 ] ) < 1 : self . log ( modules , level = logging . DEBUG ) path = ':' . join ( self . host [ 'shutit_module_path' ] ) self . log ( '\nIf you ar... | Initializes the module map of shutit based on the modules we have gathered . |
52,420 | def conn_target ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) conn_module = None for mod in self . conn_modules : if mod . module_id == self . build [ 'conn_module' ] : conn_module = mod break if conn_module is None : self . fail ( 'Couldn\'t find conn_module ' + self . build [ 'conn_module' ] ) c... | Connect to the target . |
52,421 | def finalize_target ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) self . pause_point ( '\nFinalizing the target module (' + self . shutit_main_dir + '/shutit_setup.py)' , print_input = False , level = 3 ) for mod in self . conn_modules : if mod . module_id == self . build [ 'conn_module' ] : conn_... | Finalize the target using the core finalize method . |
52,422 | def resolve_dependencies ( self , to_build , depender ) : shutit_global . shutit_global_object . yield_to_draw ( ) self . log ( 'In resolve_dependencies' , level = logging . DEBUG ) cfg = self . cfg for dependee_id in depender . depends_on : dependee = self . shutit_map . get ( dependee_id ) if ( dependee and dependee ... | Add any required dependencies . |
52,423 | def check_dependee_exists ( self , depender , dependee , dependee_id ) : shutit_global . shutit_global_object . yield_to_draw ( ) if dependee is None : return 'module: \n\n' + dependee_id + '\n\nnot found in paths: ' + str ( self . host [ 'shutit_module_path' ] ) + ' but needed for ' + depender . module_id + '\nCheck y... | Checks whether a depended - on module is available . |
52,424 | def check_dependee_build ( self , depender , dependee , dependee_id ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfg = self . cfg if not ( cfg [ dependee . module_id ] [ 'shutit.core.module.build' ] or self . is_to_be_built_or_is_installed ( dependee ) ) : return 'depender module id:\n\n[' + depender . ... | Checks whether a depended on module is configured to be built . |
52,425 | def destroy ( self ) : if self . session_type == 'bash' : self . logout ( ) elif self . session_type == 'vagrant' : self . logout ( ) | Finish up a session . |
52,426 | def shutit_method_scope ( func ) : def wrapper ( self , shutit ) : ret = func ( self , shutit ) return ret return wrapper | Notifies the ShutIt object whenever we call a shutit module method . This allows setting values for the scope of a function . |
52,427 | def managing_thread_main_simple ( ) : import shutit_global last_msg = '' while True : printed_anything = False if shutit_global . shutit_global_object . log_trace_when_idle and time . time ( ) - shutit_global . shutit_global_object . last_log_time > 10 : this_msg = '' this_header = '' for thread_id , stack in sys . _cu... | Simpler thread to track whether main thread has been quiet for long enough that a thread dump should be printed . |
52,428 | def map_package ( shutit_pexpect_session , package , install_type ) : if package in PACKAGE_MAP . keys ( ) : for itype in PACKAGE_MAP [ package ] . keys ( ) : if itype == install_type : ret = PACKAGE_MAP [ package ] [ install_type ] if isinstance ( ret , str ) : return ret if callable ( ret ) : ret ( shutit_pexpect_ses... | If package mapping exists then return it else return package . |
52,429 | def is_file_secure ( file_name ) : if not os . path . isfile ( file_name ) : return True file_mode = os . stat ( file_name ) . st_mode if file_mode & ( stat . S_IRGRP | stat . S_IWGRP | stat . S_IXGRP | stat . S_IROTH | stat . S_IWOTH | stat . S_IXOTH ) : return False return True | Returns false if file is considered insecure true if secure . If file doesn t exist it s considered secure! |
52,430 | def random_id ( size = 8 , chars = string . ascii_letters + string . digits ) : return '' . join ( random . choice ( chars ) for _ in range ( size ) ) | Generates a random string of given size from the given chars . |
52,431 | def random_word ( size = 6 ) : words = shutit_assets . get_words ( ) . splitlines ( ) word = '' while len ( word ) != size or "'" in word : word = words [ int ( random . random ( ) * ( len ( words ) - 1 ) ) ] return word . lower ( ) | Returns a random word in lower case . |
52,432 | def ctrl_c_signal_handler ( _ , frame ) : global ctrl_c_calls ctrl_c_calls += 1 if ctrl_c_calls > 10 : shutit_global . shutit_global_object . handle_exit ( exit_code = 1 ) shutit_frame = get_shutit_frame ( frame ) if in_ctrlc : msg = 'CTRL-C hit twice, quitting' if shutit_frame : shutit_global . shutit_global_object . ... | CTRL - c signal handler - enters a pause point if it can . |
52,433 | def get_input ( msg , default = '' , valid = None , boolean = False , ispass = False , color = None ) : log_trace_when_idle_original_value = shutit_global . shutit_global_object . log_trace_when_idle shutit_global . shutit_global_object . log_trace_when_idle = False if boolean and valid is None : valid = ( 'yes' , 'y' ... | Gets input from the user and returns the answer . |
52,434 | def build ( self , shutit ) : target_child = self . start_container ( shutit , 'target_child' ) self . setup_host_child ( shutit ) self . setup_target_child ( shutit , target_child ) shutit . send ( 'chmod -R 777 ' + shutit_global . shutit_global_object . shutit_state_dir + ' && mkdir -p ' + shutit_global . shutit_glob... | Sets up the target ready for building . |
52,435 | 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 . |
52,436 | 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 . |
52,437 | 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 |
52,438 | 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 |
52,439 | 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 |
52,440 | 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 |
52,441 | 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 . |
52,442 | 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 . |
52,443 | 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 . |
52,444 | 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 . |
52,445 | 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 . |
52,446 | 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 |
52,447 | def open ( cls , blob , username , password ) : return cls ( blob , blob . encryption_key ( username , password ) ) | Creates a vault from a blob object |
52,448 | 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 |
52,449 | 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 . |
52,450 | 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 . |
52,451 | 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 |
52,452 | 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 . |
52,453 | 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 |
52,454 | 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 |
52,455 | 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 |
52,456 | 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 |
52,457 | 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 |
52,458 | 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 |
52,459 | 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 . |
52,460 | 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 |
52,461 | 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 |
52,462 | 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 |
52,463 | 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 |
52,464 | 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 |
52,465 | 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 |
52,466 | 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 . |
52,467 | 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 . |
52,468 | 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 |
52,469 | 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 . |
52,470 | 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 . |
52,471 | 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 . |
52,472 | 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 . |
52,473 | 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 . |
52,474 | 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 . |
52,475 | 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 . |
52,476 | 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 . |
52,477 | 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 . |
52,478 | 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! |
52,479 | 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 . |
52,480 | 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 . |
52,481 | 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 . |
52,482 | 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 . |
52,483 | 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 |
52,484 | 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 |
52,485 | 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 . |
52,486 | 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 . |
52,487 | 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 |
52,488 | 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 |
52,489 | 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 |
52,490 | 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 |
52,491 | 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 . |
52,492 | 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 . |
52,493 | 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 . |
52,494 | 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 . |
52,495 | 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 . |
52,496 | 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 . |
52,497 | 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 |
52,498 | 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 . |
52,499 | 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.