idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
30,100 | def handle_erroneous_response ( self , response : requests . Response ) -> NoReturn : logger . debug ( "handling erroneous response: %s" , response ) try : err = BugZooException . from_dict ( response . json ( ) ) except Exception : err = UnexpectedResponse ( response ) raise err | Attempts to decode an erroneous response into an exception and to subsequently throw that exception . |
30,101 | def has_image ( self , name : str ) -> bool : path = "docker/images/{}" . format ( name ) r = self . __api . head ( path ) if r . status_code == 204 : return True elif r . status_code == 404 : return False self . __api . handle_erroneous_response ( r ) | Determines whether the server has a Docker image with a given name . |
30,102 | def delete_image ( self , name : str ) -> None : logger . debug ( "deleting Docker image: %s" , name ) path = "docker/images/{}" . format ( name ) response = self . __api . delete ( path ) if response . status_code != 204 : try : self . __api . handle_erroneous_response ( response ) except Exception : logger . exceptio... | Deletes a Docker image with a given name . |
30,103 | def _file_path ( self , container : Container , fn : str ) -> str : fn = self . resolve ( container , fn ) assert fn [ 0 ] == '/' fn = fn [ 1 : ] path = "files/{}/{}" . format ( container . uid , fn ) return path | Computes the base path for a given file . |
30,104 | def write ( self , container : Container , filepath : str , contents : str ) -> None : logger . debug ( "writing to file [%s] in container [%s]." , filepath , container . uid ) path = self . _file_path ( container , filepath ) try : response = self . __api . put ( path , data = contents ) if response . status_code != 2... | Dumps the contents of a given string into a file at a specified location inside the container . |
30,105 | def read ( self , container : Container , filepath : str ) -> str : logger . debug ( "reading contents of file [%s] in container [%s]." , filepath , container . uid ) path = self . _file_path ( container , filepath ) response = self . __api . get ( path ) if response . status_code == 200 : contents = response . text lo... | Attempts to retrieve the contents of a given file in a running container . |
30,106 | def style_similarity ( page1 , page2 ) : classes_page1 = get_classes ( page1 ) classes_page2 = get_classes ( page2 ) return jaccard_similarity ( classes_page1 , classes_page2 ) | Computes CSS style Similarity between two DOM trees |
30,107 | def restricted_to_files ( self , filenames : List [ str ] ) -> 'Spectra' : tally_passing = { fn : entries for ( fn , entries ) in self . __tally_passing . items ( ) if fn in filenames } tally_failing = { fn : entries for ( fn , entries ) in self . __tally_failing . items ( ) if fn in filenames } return Spectra ( self .... | Returns a variant of this spectra that only contains entries for lines that appear in any of the files whose name appear in the given list . |
30,108 | def filter ( self , predicate : Callable [ [ FileLine ] , 'FileLineSet' ] ) -> 'FileLineSet' : filtered = [ fileline for fileline in self if predicate ( fileline ) ] return FileLineSet . from_list ( filtered ) | Returns a subset of the file lines within this set that satisfy a given filtering criterion . |
30,109 | def union ( self , other : 'FileLineSet' ) -> 'FileLineSet' : assert isinstance ( other , FileLineSet ) l_self = list ( self ) l_other = list ( other ) l_union = l_self + l_other return FileLineSet . from_list ( l_union ) | Returns a set of file lines that contains the union of the lines within this set and a given set . |
30,110 | def intersection ( self , other : 'FileLineSet' ) -> 'FileLineSet' : assert isinstance ( other , FileLineSet ) set_self = set ( self ) set_other = set ( other ) set_union = set_self & set_other return FileLineSet . from_list ( list ( set_union ) ) | Returns a set of file lines that contains the intersection of the lines within this set and a given set . |
30,111 | def provision ( self , tool : Tool ) -> docker . models . containers . Container : if not self . is_installed ( tool ) : raise Exception ( "tool is not installed: {}" . format ( tool . name ) ) client = self . __installation . docker return client . containers . create ( tool . image ) | Provisions a mountable Docker container for a given tool . |
30,112 | def is_installed ( self , tool : Tool ) -> bool : return self . __installation . build . is_installed ( tool . image ) | Determines whether or not the Docker image for a given tool has been installed onto this server . |
30,113 | def build ( self , tool : Tool , force : bool = False , quiet : bool = False ) -> None : self . __installation . build . build ( tool . image , force = force , quiet = quiet ) | Builds the Docker image associated with a given tool . |
30,114 | def uninstall ( self , tool : Tool , force : bool = False , noprune : bool = False ) -> None : self . __installation . build . uninstall ( tool . image , force = force , noprune = noprune ) | Uninstalls all Docker images associated with this tool . |
30,115 | def to_dict ( self ) -> Dict [ str , str ] : return { 'type' : 'remote' , 'name' : self . name , 'location' : self . location , 'url' : self . url , 'version' : self . version } | Produces a dictionary - based description of this source . |
30,116 | def is_installed ( self , name : str ) -> bool : assert name is not None try : self . __docker . images . get ( name ) return True except docker . errors . ImageNotFound : return False | Indicates a given Docker image is installed on this server . |
30,117 | def build ( self , name : str , force : bool = False , quiet : bool = False ) -> None : logger . debug ( "request to build image: %s" , name ) instructions = self [ name ] if instructions . depends_on : logger . info ( "building dependent image: %s" , instructions . depends_on ) self . build ( instructions . depends_on... | Constructs a Docker image given by its name using the set of build instructions associated with that image . |
30,118 | def uninstall ( self , name : str , force : bool = False , noprune : bool = False ) -> None : try : self . __docker . images . remove ( image = name , force = force , noprune = noprune ) except docker . errors . ImageNotFound as e : if force : return raise e | Attempts to uninstall a given Docker image . |
30,119 | def upload ( self , name : str ) -> bool : try : out = self . __docker . images . push ( name , stream = True ) for line in out : line = line . strip ( ) . decode ( 'utf-8' ) jsn = json . loads ( line ) if 'progress' in jsn : line = "{}. {}." . format ( jsn [ 'status' ] , jsn [ 'progress' ] ) print ( line , end = '\r' ... | Attempts to upload a given Docker image from this server to DockerHub . |
30,120 | def printflush ( s : str , end : str = '\n' ) -> None : print ( s , end = end ) sys . stdout . flush ( ) | Prints a given string to the standard output and immediately flushes . |
30,121 | def from_dict ( d : Dict [ str , Any ] ) -> 'CoverageInstructions' : name_type = d [ 'type' ] cls = _NAME_TO_INSTRUCTIONS [ name_type ] return cls . from_dict ( d ) | Loads a set of coverage instructions from a given dictionary . |
30,122 | def object_deserializer ( obj ) : for key , val in obj . items ( ) : if isinstance ( val , six . string_types ) and DATETIME_REGEX . search ( val ) : try : obj [ key ] = dates . localize_datetime ( parser . parse ( val ) ) except ValueError : obj [ key ] = val return obj | Helper to deserialize a raw result dict into a proper dict . |
30,123 | def login ( session , user , password , database = None , server = None ) : if not user : user = click . prompt ( "Username" , type = str ) if not password : password = click . prompt ( "Password" , hide_input = True , type = str ) try : with click . progressbar ( length = 1 , label = "Logging in..." ) as progressbar :... | Logs into a MyGeotab server and stores the returned credentials . |
30,124 | def sessions ( session ) : active_sessions = session . get_sessions ( ) if not active_sessions : click . echo ( '(No active sessions)' ) return for active_session in active_sessions : click . echo ( active_session ) | Shows the current logged in sessions . |
30,125 | def console ( session , database = None , user = None , password = None , server = None ) : local_vars = _populate_locals ( database , password , server , session , user ) version = 'MyGeotab Console {0} [Python {1}]' . format ( mygeotab . __version__ , sys . version . replace ( '\n' , '' ) ) auth_line = ( 'Logged in a... | An interactive Python API console for MyGeotab |
30,126 | def run ( * tasks : Awaitable , loop : asyncio . AbstractEventLoop = asyncio . get_event_loop ( ) ) : futures = [ asyncio . ensure_future ( task , loop = loop ) for task in tasks ] return loop . run_until_complete ( asyncio . gather ( * futures ) ) | Helper to run tasks in the event loop |
30,127 | async def server_call_async ( method , server , loop : asyncio . AbstractEventLoop = asyncio . get_event_loop ( ) , timeout = DEFAULT_TIMEOUT , verify_ssl = True , ** parameters ) : if method is None : raise Exception ( "A method name must be specified" ) if server is None : raise Exception ( "A server (eg. my3.geotab.... | Makes an asynchronous call to an un - authenticated method on a server . |
30,128 | async def _query ( server , method , parameters , timeout = DEFAULT_TIMEOUT , verify_ssl = True , loop : asyncio . AbstractEventLoop = None ) : api_endpoint = api . get_api_url ( server ) params = dict ( id = - 1 , method = method , params = parameters ) headers = get_headers ( ) ssl_context = None verify = verify_ssl ... | Formats and performs the asynchronous query against the API |
30,129 | async def call_async ( self , method , ** parameters ) : if method is None : raise Exception ( 'A method name must be specified' ) params = api . process_parameters ( parameters ) if self . credentials and not self . credentials . session_id : self . authenticate ( ) if 'credentials' not in params and self . credential... | Makes an async call to the API . |
30,130 | async def multi_call_async ( self , calls ) : formatted_calls = [ dict ( method = call [ 0 ] , params = call [ 1 ] if len ( call ) > 1 else { } ) for call in calls ] return await self . call_async ( 'ExecuteMultiCall' , calls = formatted_calls ) | Performs an async multi - call to the API |
30,131 | def from_credentials ( credentials , loop : asyncio . AbstractEventLoop = asyncio . get_event_loop ( ) ) : return API ( username = credentials . username , password = credentials . password , database = credentials . database , session_id = credentials . session_id , server = credentials . server , loop = loop ) | Returns a new async API object from an existing Credentials object . |
30,132 | def format_iso_datetime ( datetime_obj ) : datetime_obj = localize_datetime ( datetime_obj , pytz . utc ) if datetime_obj < MIN_DATE : datetime_obj = MIN_DATE elif datetime_obj > MAX_DATE : datetime_obj = MAX_DATE return datetime_obj . replace ( tzinfo = None ) . strftime ( '%Y-%m-%dT%H:%M:%S.%f' ) [ : - 3 ] + 'Z' | Formats the given datetime as a UTC - zoned ISO 8601 date string . |
30,133 | def localize_datetime ( datetime_obj , tz = pytz . utc ) : if not datetime_obj . tzinfo : return tz . localize ( datetime_obj ) else : try : return datetime_obj . astimezone ( tz ) except OverflowError : if datetime_obj < datetime ( 2 , 1 , 1 , tzinfo = pytz . utc ) : return MIN_DATE . astimezone ( tz ) return MAX_DATE... | Converts a naive or UTC - localized date into the provided timezone . |
30,134 | def _run ( self ) : while self . running : try : result = self . client_api . call ( 'GetFeed' , type_name = self . type_name , search = self . search , from_version = self . _version , results_limit = self . results_limit ) self . _version = result [ 'toVersion' ] self . listener . on_data ( result [ 'data' ] ) except... | Runner for the Data Feed . |
30,135 | def start ( self , threaded = True ) : self . running = True if threaded : self . _thread = Thread ( target = self . _run ) self . _thread . start ( ) else : self . _run ( ) | Start the data feed . |
30,136 | def _query ( server , method , parameters , timeout = DEFAULT_TIMEOUT , verify_ssl = True ) : api_endpoint = get_api_url ( server ) params = dict ( id = - 1 , method = method , params = parameters or { } ) headers = get_headers ( ) with requests . Session ( ) as session : session . mount ( 'https://' , GeotabHTTPAdapte... | Formats and performs the query against the API . |
30,137 | def server_call ( method , server , timeout = DEFAULT_TIMEOUT , verify_ssl = True , ** parameters ) : if method is None : raise Exception ( "A method name must be specified" ) if server is None : raise Exception ( "A server (eg. my3.geotab.com) must be specified" ) parameters = process_parameters ( parameters ) return ... | Makes a call to an un - authenticated method on a server |
30,138 | def process_parameters ( parameters ) : if not parameters : return { } params = copy . copy ( parameters ) for param_name in parameters : value = parameters [ param_name ] server_param_name = re . sub ( r'_(\w)' , lambda m : m . group ( 1 ) . upper ( ) , param_name ) if isinstance ( value , dict ) : value = process_par... | Allows the use of Pythonic - style parameters with underscores instead of camel - case . |
30,139 | def get_api_url ( server ) : parsed = urlparse ( server ) base_url = parsed . netloc if parsed . netloc else parsed . path base_url . replace ( '/' , '' ) return 'https://' + base_url + '/apiv1' | Formats the server URL properly in order to query the API . |
30,140 | def multi_call ( self , calls ) : formatted_calls = [ dict ( method = call [ 0 ] , params = call [ 1 ] if len ( call ) > 1 else { } ) for call in calls ] return self . call ( 'ExecuteMultiCall' , calls = formatted_calls ) | Performs a multi - call to the API . |
30,141 | def authenticate ( self , is_global = True ) : auth_data = dict ( database = self . credentials . database , userName = self . credentials . username , password = self . credentials . password ) auth_data [ 'global' ] = is_global try : result = _query ( self . _server , 'Authenticate' , auth_data , self . timeout , ver... | Authenticates against the API server . |
30,142 | def from_credentials ( credentials ) : return API ( username = credentials . username , password = credentials . password , database = credentials . database , session_id = credentials . session_id , server = credentials . server ) | Returns a new API object from an existing Credentials object . |
30,143 | def _populate_sub_entity ( self , entity , type_name ) : key = type_name . lower ( ) if isinstance ( entity [ key ] , str ) : entity [ key ] = dict ( id = entity [ key ] ) return cache = self . _cache [ key ] subentity = cache . get ( entity [ key ] [ 'id' ] ) if not subentity : subentities = self . api . get ( type_na... | Simple API - backed cache for populating MyGeotab entities |
30,144 | def on_data ( self , data ) : for d in data : self . _populate_sub_entity ( d , 'Device' ) self . _populate_sub_entity ( d , 'Rule' ) date = dates . localize_datetime ( d [ 'activeFrom' ] ) click . echo ( '[{date}] {device} ({rule})' . format ( date = date , device = d [ 'device' ] . get ( 'name' , '**Unknown Vehicle' ... | The function called when new data has arrived . |
30,145 | def _should_allocate_port ( pid ) : if pid <= 0 : log . info ( 'Not allocating a port to invalid pid' ) return False if pid == 1 : log . info ( 'Not allocating a port to init.' ) return False try : os . kill ( pid , 0 ) except ProcessLookupError : log . info ( 'Not allocating a port to a non-existent process' ) return ... | Determine if we should allocate a port for use by the given process id . |
30,146 | def _parse_command_line ( ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( '--portserver_static_pool' , type = str , default = '15000-24999' , help = 'Comma separated N-P Range(s) of ports to manage (inclusive).' ) parser . add_argument ( '--portserver_unix_socket_address' , type = str , default = '@u... | Configure and parse our command line flags . |
30,147 | def _parse_port_ranges ( pool_str ) : ports = set ( ) for range_str in pool_str . split ( ',' ) : try : a , b = range_str . split ( '-' , 1 ) start , end = int ( a ) , int ( b ) except ValueError : log . error ( 'Ignoring unparsable port range %r.' , range_str ) continue if start < 1 or end > 65535 : log . error ( 'Ign... | Given a N - P X - Y description of port ranges return a set of ints . |
30,148 | def _configure_logging ( verbose = False , debug = False ) : overall_level = logging . DEBUG if debug else logging . INFO logging . basicConfig ( format = ( '{levelname[0]}{asctime}.{msecs:03.0f} {thread} ' '{filename}:{lineno}] {message}' ) , datefmt = '%m%d %H:%M:%S' , style = '{' , level = overall_level ) global log... | Configure the log global message format and verbosity settings . |
30,149 | def get_port_for_process ( self , pid ) : if not self . _port_queue : raise RuntimeError ( 'No ports being managed.' ) check_count = 0 max_ports_to_test = len ( self . _port_queue ) while check_count < max_ports_to_test : candidate = self . _port_queue . pop ( ) self . _port_queue . appendleft ( candidate ) check_count... | Allocates and returns port for pid or 0 if none could be allocated . |
30,150 | def add_port_to_free_pool ( self , port ) : if port < 1 or port > 65535 : raise ValueError ( 'Port must be in the [1, 65535] range, not %d.' % port ) port_info = _PortInfo ( port = port ) self . _port_queue . append ( port_info ) | Add a new port to the free pool for allocation . |
30,151 | def _handle_port_request ( self , client_data , writer ) : try : pid = int ( client_data ) except ValueError as error : self . _client_request_errors += 1 log . warning ( 'Could not parse request: %s' , error ) return log . info ( 'Request on behalf of pid %d.' , pid ) log . info ( 'cmdline: %s' , _get_process_command_... | Given a port request body parse it and respond appropriately . |
30,152 | def dump_stats ( self ) : log . info ( 'Dumping statistics:' ) stats = [ ] stats . append ( 'client-request-errors {}' . format ( self . _client_request_errors ) ) stats . append ( 'denied-allocations {}' . format ( self . _denied_allocations ) ) stats . append ( 'num-ports-managed {}' . format ( self . _port_pool . nu... | Logs statistics of our operation . |
30,153 | def return_port ( port ) : if port in _random_ports : _random_ports . remove ( port ) elif port in _owned_ports : _owned_ports . remove ( port ) _free_ports . add ( port ) elif port in _free_ports : logging . info ( "Returning a port that was already returned: %s" , port ) else : logging . info ( "Returning a port that... | Return a port that is no longer being used so it can be reused . |
30,154 | def bind ( port , socket_type , socket_proto ) : got_socket = False for family in ( socket . AF_INET6 , socket . AF_INET ) : try : sock = socket . socket ( family , socket_type , socket_proto ) got_socket = True except socket . error : continue try : sock . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 )... | Try to bind to a socket of the specified type protocol and port . |
30,155 | def pick_unused_port ( pid = None , portserver_address = None ) : try : port = _free_ports . pop ( ) except KeyError : pass else : _owned_ports . add ( port ) return port if portserver_address : port = get_port_from_port_server ( portserver_address , pid = pid ) if port : return port if 'PORTSERVER_ADDRESS' in os . env... | A pure python implementation of PickUnusedPort . |
30,156 | def _pick_unused_port_without_server ( ) : rng = random . Random ( ) for _ in range ( 10 ) : port = int ( rng . randrange ( 15000 , 25000 ) ) if is_port_free ( port ) : _random_ports . add ( port ) return port for _ in range ( 10 ) : port = bind ( 0 , _PROTOS [ 0 ] [ 0 ] , _PROTOS [ 0 ] [ 1 ] ) if port and bind ( port ... | Pick an available network port without the help of a port server . |
30,157 | def get_port_from_port_server ( portserver_address , pid = None ) : if not portserver_address : return None if portserver_address [ 0 ] == '@' : portserver_address = '\0' + portserver_address [ 1 : ] if pid is None : pid = os . getpid ( ) try : if hasattr ( socket , 'AF_UNIX' ) : sock = socket . socket ( socket . AF_UN... | Request a free a port from a system - wide portserver . |
30,158 | def main ( argv ) : port = pick_unused_port ( pid = int ( argv [ 1 ] ) if len ( argv ) > 1 else None ) if not port : sys . exit ( 1 ) print ( port ) | If passed an arg treat it as a PID otherwise portpicker uses getpid . |
30,159 | def soap_request ( self , url , urn , action , params , body_elem = "m" ) : soap_body = ( '<?xml version="1.0" encoding="utf-8"?>' '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"' ' s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' '<s:Body>' '<{body_elem}:{action} xmlns:{body_elem}="urn:{u... | Send a SOAP request to the TV . |
30,160 | def _get_local_ip ( self ) : try : sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM ) sock . connect ( ( '8.8.8.8' , 80 ) ) return sock . getsockname ( ) [ 0 ] except socket . error : try : return socket . gethostbyname ( socket . gethostname ( ) ) except socket . gaierror : return '127.0.0.1' finally : ... | Try to determine the local IP address of the machine . |
30,161 | def open_webpage ( self , url ) : params = ( '<X_AppType>vc_app</X_AppType>' '<X_LaunchKeyword>resource_id={resource_id}</X_LaunchKeyword>' ) . format ( resource_id = 1063 ) res = self . soap_request ( URL_CONTROL_NRC , URN_REMOTE_CONTROL , 'X_LaunchApp' , params , body_elem = "s" ) root = ET . fromstring ( res ) el_se... | Launch Web Browser and open url |
30,162 | def get_volume ( self ) : params = '<InstanceID>0</InstanceID><Channel>Master</Channel>' res = self . soap_request ( URL_CONTROL_DMR , URN_RENDERING_CONTROL , 'GetVolume' , params ) root = ET . fromstring ( res ) el_volume = root . find ( './/CurrentVolume' ) return int ( el_volume . text ) | Return the current volume level . |
30,163 | def set_volume ( self , volume ) : if volume > 100 or volume < 0 : raise Exception ( 'Bad request to volume control. ' 'Must be between 0 and 100' ) params = ( '<InstanceID>0</InstanceID><Channel>Master</Channel>' '<DesiredVolume>{}</DesiredVolume>' ) . format ( volume ) self . soap_request ( URL_CONTROL_DMR , URN_REND... | Set a new volume level . |
30,164 | def get_mute ( self ) : params = '<InstanceID>0</InstanceID><Channel>Master</Channel>' res = self . soap_request ( URL_CONTROL_DMR , URN_RENDERING_CONTROL , 'GetMute' , params ) root = ET . fromstring ( res ) el_mute = root . find ( './/CurrentMute' ) return el_mute . text != '0' | Return if the TV is muted . |
30,165 | def set_mute ( self , enable ) : data = '1' if enable else '0' params = ( '<InstanceID>0</InstanceID><Channel>Master</Channel>' '<DesiredMute>{}</DesiredMute>' ) . format ( data ) self . soap_request ( URL_CONTROL_DMR , URN_RENDERING_CONTROL , 'SetMute' , params ) | Mute or unmute the TV . |
30,166 | def send_key ( self , key ) : if isinstance ( key , Keys ) : key = key . value params = '<X_KeyEvent>{}</X_KeyEvent>' . format ( key ) self . soap_request ( URL_CONTROL_NRC , URN_REMOTE_CONTROL , 'X_SendKey' , params ) | Send a key command to the TV . |
30,167 | def main ( ) : parser = argparse . ArgumentParser ( prog = 'panasonic_viera' , description = 'Remote control a Panasonic Viera TV.' ) parser . add_argument ( 'host' , metavar = 'host' , type = str , help = 'Address of the Panasonic Viera TV' ) parser . add_argument ( 'port' , metavar = 'port' , type = int , nargs = '?'... | Handle command line execution . |
30,168 | def item ( self , name , fuzzy_threshold = 100 ) : match = process . extractOne ( name , self . _items . keys ( ) , score_cutoff = ( fuzzy_threshold - 1 ) , ) if match : exact_name = match [ 0 ] item = self . _items [ exact_name ] item . decrypt_with ( self ) return item else : return None | Extract a password from an unlocked Keychain using fuzzy matching . fuzzy_threshold can be an integer between 0 and 100 where 100 is an exact match . |
30,169 | def key ( self , identifier = None , security_level = None ) : if identifier : try : return self . _encryption_keys [ identifier ] except KeyError : pass if security_level : for key in self . _encryption_keys . values ( ) : if key . level == security_level : return key | Tries to find an encryption key first using the identifier and if that fails or isn t provided using the security_level . Returns None if nothing matches . |
30,170 | def run ( self ) : self . _unlock_keychain ( ) item = self . keychain . item ( self . arguments . item , fuzzy_threshold = self . _fuzzy_threshold ( ) , ) if item is not None : self . stdout . write ( "%s\n" % item . password ) else : self . stderr . write ( "1pass: Could not find an item named '%s'\n" % ( self . argum... | The main entry point performs the appropriate action for the given arguments . |
30,171 | def is_text ( bytesio ) : text_chars = ( bytearray ( [ 7 , 8 , 9 , 10 , 11 , 12 , 13 , 27 ] ) + bytearray ( range ( 0x20 , 0x7F ) ) + bytearray ( range ( 0x80 , 0X100 ) ) ) return not bool ( bytesio . read ( 1024 ) . translate ( None , text_chars ) ) | Return whether the first KB of contents seems to be binary . |
30,172 | def parse_shebang ( bytesio ) : if bytesio . read ( 2 ) != b'#!' : return ( ) first_line = bytesio . readline ( ) try : first_line = first_line . decode ( 'UTF-8' ) except UnicodeDecodeError : return ( ) for c in first_line : if c not in printable : return ( ) cmd = tuple ( _shebang_split ( first_line . strip ( ) ) ) i... | Parse the shebang from a file opened for reading binary . |
30,173 | def parse_shebang_from_file ( path ) : if not os . path . lexists ( path ) : raise ValueError ( '{} does not exist.' . format ( path ) ) if not os . access ( path , os . X_OK ) : return ( ) with open ( path , 'rb' ) as f : return parse_shebang ( f ) | Parse the shebang given a file path . |
30,174 | def license_id ( filename ) : import editdistance with io . open ( filename , encoding = 'UTF-8' ) as f : contents = f . read ( ) norm = _norm_license ( contents ) min_edit_dist = sys . maxsize min_edit_dist_spdx = '' for spdx , text in licenses . LICENSES : norm_license = _norm_license ( text ) if norm == norm_license... | Return the spdx id for the license contained in filename . If no license is detected returns None . |
30,175 | def access_token ( self ) : if self . cache_token : return self . access_token_ or self . _resolve_credential ( 'access_token' ) return self . access_token_ | Get access_token . |
30,176 | def _credentials_found_in_envars ( ) : return any ( [ os . getenv ( 'PAN_ACCESS_TOKEN' ) , os . getenv ( 'PAN_CLIENT_ID' ) , os . getenv ( 'PAN_CLIENT_SECRET' ) , os . getenv ( 'PAN_REFRESH_TOKEN' ) ] ) | Check for credentials in envars . |
30,177 | def _resolve_credential ( self , credential ) : if self . _credentials_found_in_instance : return elif self . _credentials_found_in_envars ( ) : return os . getenv ( 'PAN_' + credential . upper ( ) ) else : return self . storage . fetch_credential ( credential = credential , profile = self . profile ) | Resolve credential from envars or credentials store . |
30,178 | def decode_jwt_payload ( self , access_token = None ) : c = self . get_credentials ( ) jwt = access_token or c . access_token try : _ , payload , _ = jwt . split ( '.' ) rem = len ( payload ) % 4 if rem > 0 : payload += '=' * ( 4 - rem ) try : decoded_jwt = b64decode ( payload ) . decode ( "utf-8" ) except TypeError as... | Extract payload field from JWT . |
30,179 | def _decode_exp ( self , access_token = None ) : c = self . get_credentials ( ) jwt = access_token or c . access_token x = self . decode_jwt_payload ( jwt ) if 'exp' in x : try : exp = int ( x [ 'exp' ] ) except ValueError : raise PanCloudError ( "Expiration time (exp) must be an integer" ) else : self . jwt_exp = exp ... | Extract exp field from access token . |
30,180 | def fetch_tokens ( self , client_id = None , client_secret = None , code = None , redirect_uri = None , ** kwargs ) : client_id = client_id or self . client_id client_secret = client_secret or self . client_secret redirect_uri = redirect_uri or self . redirect_uri data = { 'grant_type' : 'authorization_code' , 'client_... | Exchange authorization code for token . |
30,181 | def get_authorization_url ( self , client_id = None , instance_id = None , redirect_uri = None , region = None , scope = None , state = None ) : client_id = client_id or self . client_id instance_id = instance_id or self . instance_id redirect_uri = redirect_uri or self . redirect_uri region = region or self . region s... | Generate authorization URL . |
30,182 | def get_credentials ( self ) : return ReadOnlyCredentials ( self . access_token , self . client_id , self . client_secret , self . refresh_token ) | Get read - only credentials . |
30,183 | def jwt_is_expired ( self , access_token = None , leeway = 0 ) : if access_token is not None : exp = self . _decode_exp ( access_token ) else : exp = self . jwt_exp now = time ( ) if exp < ( now - leeway ) : return True return False | Validate JWT access token expiration . |
30,184 | def refresh ( self , access_token = None , ** kwargs ) : if not self . token_lock . locked ( ) : with self . token_lock : if access_token == self . access_token or access_token is None : if self . developer_token is not None : r = self . _httpclient . request ( method = 'POST' , url = self . developer_token_url , path ... | Refresh access and refresh tokens . |
30,185 | def revoke_access_token ( self , ** kwargs ) : c = self . get_credentials ( ) data = { 'client_id' : c . client_id , 'client_secret' : c . client_secret , 'token' : c . access_token , 'token_type_hint' : 'access_token' } r = self . _httpclient . request ( method = 'POST' , url = self . token_url , json = data , path = ... | Revoke access token . |
30,186 | def delete ( self , query_id = None , ** kwargs ) : path = "/logging-service/v1/queries/{}" . format ( query_id ) r = self . _httpclient . request ( method = "DELETE" , url = self . url , path = path , ** kwargs ) return r | Delete a query job . |
30,187 | def iter_poll ( self , query_id = None , sequence_no = None , params = None , ** kwargs ) : while True : r = self . poll ( query_id , sequence_no , params , enforce_json = True , ** kwargs ) if r . json ( ) [ 'queryStatus' ] == "FINISHED" : if sequence_no is not None : sequence_no += 1 else : sequence_no = 1 yield r el... | Retrieve pages iteratively in a non - greedy manner . |
30,188 | def poll ( self , query_id = None , sequence_no = None , params = None , ** kwargs ) : path = "/logging-service/v1/queries/{}/{}" . format ( query_id , sequence_no ) r = self . _httpclient . request ( method = "GET" , url = self . url , params = params , path = path , ** kwargs ) return r | Poll for asynchronous query results . |
30,189 | def xpoll ( self , query_id = None , sequence_no = None , params = None , delete_query = True , ** kwargs ) : def _delete ( query_id , ** kwargs ) : r = self . delete ( query_id , ** kwargs ) try : r_json = r . json ( ) except ValueError as e : raise PanCloudError ( 'Invalid JSON: %s' % e ) if not ( 200 <= r . status_c... | Retrieve individual logs iteratively in a non - greedy manner . |
30,190 | def write ( self , vendor_id = None , log_type = None , json = None , ** kwargs ) : path = "/logging-service/v1/logs/{}/{}" . format ( vendor_id , log_type ) r = self . _httpclient . request ( method = "POST" , url = self . url , json = json , path = path , ** kwargs ) return r | Write log records to the Logging Service . |
30,191 | def fetch_credential ( self , credential = None , profile = None ) : q = self . db . get ( self . query . profile == profile ) if q is not None : return q . get ( credential ) | Fetch credential from credentials file . |
30,192 | def remove_profile ( self , profile = None ) : with self . db : return self . db . remove ( self . query . profile == profile ) | Remove profile from credentials file . |
30,193 | def nack ( self , channel_id = None , ** kwargs ) : path = "/event-service/v1/channels/{}/nack" . format ( channel_id ) r = self . _httpclient . request ( method = "POST" , url = self . url , path = path , ** kwargs ) return r | Send a negative read - acknowledgement to the service . |
30,194 | def poll ( self , channel_id = None , json = None , ** kwargs ) : path = "/event-service/v1/channels/{}/poll" . format ( channel_id ) r = self . _httpclient . request ( method = "POST" , url = self . url , json = json , path = path , ** kwargs ) return r | Read one or more events from a channel . |
30,195 | def xpoll ( self , channel_id = None , json = None , ack = False , follow = False , pause = None , ** kwargs ) : def _ack ( channel_id , ** kwargs ) : r = self . ack ( channel_id , ** kwargs ) if not ( 200 <= r . status_code < 300 ) : try : r_json = r . json ( ) except ValueError as e : raise PanCloudError ( 'Invalid J... | Retrieve logType event entries iteratively in a non - greedy manner . |
30,196 | def _apply_credentials ( auto_refresh = True , credentials = None , headers = None ) : token = credentials . get_credentials ( ) . access_token if auto_refresh is True : if token is None : token = credentials . refresh ( access_token = None , timeout = 10 ) elif credentials . jwt_is_expired ( ) : token = credentials . ... | Update Authorization header . |
30,197 | def request ( self , ** kwargs ) : url = kwargs . pop ( 'url' , self . url ) auth = kwargs . pop ( 'auth' , self . session . auth ) cert = kwargs . pop ( 'cert' , self . session . cert ) cookies = kwargs . pop ( 'cookies' , self . session . cookies ) headers = kwargs . pop ( 'headers' , self . session . headers . copy ... | Generate HTTP request using given parameters . |
30,198 | def query ( self , object_class = None , json = None , ** kwargs ) : path = "/directory-sync-service/v1/{}" . format ( object_class ) r = self . _httpclient . request ( method = "POST" , url = self . url , json = json , path = path , ** kwargs ) return r | Query data stored in directory . |
30,199 | def handle ( self , * args , ** options ) : if options [ "sub_command" ] == "add" : self . handle_add ( options ) elif options [ "sub_command" ] == "update" : self . handle_update ( options ) elif options [ "sub_command" ] == "details" : self . handle_details ( options [ "username" ] ) elif options [ "sub_command" ] ==... | Forward to the right sub - handler |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.