idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
234,000
def terminate ( self ) : self . toggle_scan ( False ) self . keep_going = False self . join ( )
Signal runner to stop and join thread .
234,001
def data_to_uuid ( data ) : string = data_to_hexstring ( data ) return string [ 0 : 8 ] + '-' + string [ 8 : 12 ] + '-' + string [ 12 : 16 ] + '-' + string [ 16 : 20 ] + '-' + string [ 20 : 32 ]
Convert an array of binary data to the iBeacon uuid format .
234,002
def bt_addr_to_string ( addr ) : addr_str = array . array ( 'B' , addr ) addr_str . reverse ( ) hex_str = hexlify ( addr_str . tostring ( ) ) . decode ( 'ascii' ) return ':' . join ( a + b for a , b in zip ( hex_str [ : : 2 ] , hex_str [ 1 : : 2 ] ) )
Convert a binary string to the hex representation .
234,003
def is_one_of ( obj , types ) : for type_ in types : if isinstance ( obj , type_ ) : return True return False
Return true iff obj is an instance of one of the types .
234,004
def is_packet_type ( cls ) : from . packet_types import EddystoneUIDFrame , EddystoneURLFrame , EddystoneEncryptedTLMFrame , EddystoneTLMFrame , EddystoneEIDFrame , IBeaconAdvertisement , EstimoteTelemetryFrameA , EstimoteTelemetryFrameB return ( cls in [ EddystoneURLFrame , EddystoneUIDFrame , EddystoneEncryptedTLMFra...
Check if class is one the packet types .
234,005
def bin_to_int ( string ) : if isinstance ( string , str ) : return struct . unpack ( "b" , string ) [ 0 ] else : return struct . unpack ( "b" , bytes ( [ string ] ) ) [ 0 ]
Convert a one element byte string to signed int for python 2 support .
234,006
def get_mode ( device_filter ) : from . device_filters import IBeaconFilter , EddystoneFilter , BtAddrFilter , EstimoteFilter if device_filter is None or len ( device_filter ) == 0 : return ScannerMode . MODE_ALL mode = ScannerMode . MODE_NONE for filtr in device_filter : if isinstance ( filtr , IBeaconFilter ) : mode ...
Determine which beacons the scanner should look for .
234,007
def matches ( self , filter_props ) : if filter_props is None : return False found_one = False for key , value in filter_props . items ( ) : if key in self . properties and value != self . properties [ key ] : return False elif key in self . properties and value == self . properties [ key ] : found_one = True return fo...
Check if the filter matches the supplied properties .
234,008
def parse_packet ( packet ) : frame = parse_ltv_packet ( packet ) if frame is None : frame = parse_ibeacon_packet ( packet ) return frame
Parse a beacon advertisement packet .
234,009
def parse_ltv_packet ( packet ) : try : frame = LTVFrame . parse ( packet ) for ltv in frame : if ltv [ 'type' ] == SERVICE_DATA_TYPE : data = ltv [ 'value' ] if data [ "service_identifier" ] == EDDYSTONE_UUID : return parse_eddystone_service_data ( data ) elif data [ "service_identifier" ] == ESTIMOTE_UUID : return pa...
Parse a tag - length - value style beacon packet .
234,010
def parse_eddystone_service_data ( data ) : if data [ 'frame_type' ] == EDDYSTONE_UID_FRAME : return EddystoneUIDFrame ( data [ 'frame' ] ) elif data [ 'frame_type' ] == EDDYSTONE_TLM_FRAME : if data [ 'frame' ] [ 'tlm_version' ] == EDDYSTONE_TLM_ENCRYPTED : return EddystoneEncryptedTLMFrame ( data [ 'frame' ] [ 'data'...
Parse Eddystone service data .
234,011
def parse_estimote_service_data ( data ) : if data [ 'frame_type' ] & 0xF == ESTIMOTE_TELEMETRY_FRAME : protocol_version = ( data [ 'frame_type' ] & 0xF0 ) >> 4 if data [ 'frame' ] [ 'subframe_type' ] == ESTIMOTE_TELEMETRY_SUBFRAME_A : return EstimoteTelemetryFrameA ( data [ 'frame' ] , protocol_version ) elif data [ '...
Parse Estimote service data .
234,012
def parse_motion_state ( val ) : number = val & 0b00111111 unit = ( val & 0b11000000 ) >> 6 if unit == 1 : number *= 60 elif unit == 2 : number *= 60 * 60 elif unit == 3 and number < 32 : number *= 60 * 60 * 24 elif unit == 3 : number -= 32 number *= 60 * 60 * 24 * 7 return number
Convert motion state byte to seconds .
234,013
def monkey_patch ( cls ) : on_read_the_docs = os . environ . get ( 'READTHEDOCS' , False ) if on_read_the_docs : sys . modules [ 'zbarlight._zbarlight' ] = cls
Monkey path zbarlight C extension on Read The Docs
234,014
def set_pixel ( framebuf , x , y , color ) : index = ( y >> 3 ) * framebuf . stride + x offset = y & 0x07 framebuf . buf [ index ] = ( framebuf . buf [ index ] & ~ ( 0x01 << offset ) ) | ( ( color != 0 ) << offset )
Set a given pixel to a color .
234,015
def get_pixel ( framebuf , x , y ) : index = ( y >> 3 ) * framebuf . stride + x offset = y & 0x07 return ( framebuf . buf [ index ] >> offset ) & 0x01
Get the color of a given pixel
234,016
def pixel ( self , x , y , color = None ) : if self . rotation == 1 : x , y = y , x x = self . width - x - 1 if self . rotation == 2 : x = self . width - x - 1 y = self . height - y - 1 if self . rotation == 3 : x , y = y , x y = self . height - y - 1 if x < 0 or x >= self . width or y < 0 or y >= self . height : retur...
If color is not given get the color value of the specified pixel . If color is given set the specified pixel to the given color .
234,017
def hline ( self , x , y , width , color ) : self . rect ( x , y , width , 1 , color , fill = True )
Draw a horizontal line up to a given length .
234,018
def vline ( self , x , y , height , color ) : self . rect ( x , y , 1 , height , color , fill = True )
Draw a vertical line up to a given length .
234,019
def rect ( self , x , y , width , height , color , * , fill = False ) : if self . rotation == 1 : x , y = y , x width , height = height , width x = self . width - x - width if self . rotation == 2 : x = self . width - x - width y = self . height - y - height if self . rotation == 3 : x , y = y , x width , height = heig...
Draw a rectangle at the given location size and color . The rect method draws only a 1 pixel outline .
234,020
def line ( self , x_0 , y_0 , x_1 , y_1 , color ) : d_x = abs ( x_1 - x_0 ) d_y = abs ( y_1 - y_0 ) x , y = x_0 , y_0 s_x = - 1 if x_0 > x_1 else 1 s_y = - 1 if y_0 > y_1 else 1 if d_x > d_y : err = d_x / 2.0 while x != x_1 : self . pixel ( x , y , color ) err -= d_y if err < 0 : y += s_y err += d_x x += s_x else : err...
Bresenham s line algorithm
234,021
def scroll ( self , delta_x , delta_y ) : if delta_x < 0 : shift_x = 0 xend = self . width + delta_x dt_x = 1 else : shift_x = self . width - 1 xend = delta_x - 1 dt_x = - 1 if delta_y < 0 : y = 0 yend = self . height + delta_y dt_y = 1 else : y = self . height - 1 yend = delta_y - 1 dt_y = - 1 while y != yend : x = sh...
shifts framebuf in x and y direction
234,022
def text ( self , string , x , y , color , * , font_name = "font5x8.bin" ) : if not self . _font or self . _font . font_name != font_name : self . _font = BitmapFont ( ) w = self . _font . font_width for i , char in enumerate ( string ) : self . _font . draw_char ( char , x + ( i * ( w + 1 ) ) , y , self , color )
text is not yet implemented
234,023
def parse_auth_token_from_request ( self , auth_header ) : if not auth_header : raise falcon . HTTPUnauthorized ( description = 'Missing Authorization Header' ) parts = auth_header . split ( ) if parts [ 0 ] . lower ( ) != self . auth_header_prefix . lower ( ) : raise falcon . HTTPUnauthorized ( description = 'Invalid ...
Parses and returns Auth token from the request header . Raises falcon . HTTPUnauthoried exception with proper error message
234,024
def authenticate ( self , req , resp , resource ) : payload = self . _decode_jwt_token ( req ) user = self . user_loader ( payload ) if not user : raise falcon . HTTPUnauthorized ( description = 'Invalid JWT Credentials' ) return user
Extract auth token from request authorization header decode jwt token verify configured claims and return either a user object if successful else raise an falcon . HTTPUnauthoried exception
234,025
def get_auth_token ( self , user_payload ) : now = datetime . utcnow ( ) payload = { 'user' : user_payload } if 'iat' in self . verify_claims : payload [ 'iat' ] = now if 'nbf' in self . verify_claims : payload [ 'nbf' ] = now + self . leeway if 'exp' in self . verify_claims : payload [ 'exp' ] = now + self . expiratio...
Create a JWT authentication token from user_payload
234,026
def get_auth_token ( self , user_payload ) : token = user_payload . get ( 'token' ) or None if not token : raise ValueError ( '`user_payload` must provide api token' ) return '{auth_header_prefix} {token}' . format ( auth_header_prefix = self . auth_header_prefix , token = token )
Extracts token from the user_payload
234,027
def parse_auth_token_from_request ( self , auth_header ) : if not auth_header : raise falcon . HTTPUnauthorized ( description = 'Missing Authorization Header' ) try : auth_header_prefix , _ = auth_header . split ( ' ' , 1 ) except ValueError : raise falcon . HTTPUnauthorized ( description = 'Invalid Authorization Heade...
Parses and returns the Hawk Authorization header if it is present and well - formed . Raises falcon . HTTPUnauthoried exception with proper error message
234,028
def _apply_base_theme ( app ) : if QT_VERSION < ( 5 , ) : app . setStyle ( 'plastique' ) else : app . setStyle ( 'Fusion' ) with open ( _STYLESHEET ) as stylesheet : app . setStyleSheet ( stylesheet . read ( ) )
Apply base theme to the application .
234,029
def dark ( app ) : _apply_base_theme ( app ) darkPalette = QPalette ( ) darkPalette . setColor ( QPalette . WindowText , QColor ( 180 , 180 , 180 ) ) darkPalette . setColor ( QPalette . Button , QColor ( 53 , 53 , 53 ) ) darkPalette . setColor ( QPalette . Light , QColor ( 180 , 180 , 180 ) ) darkPalette . setColor ( Q...
Apply Dark Theme to the Qt application instance .
234,030
def inheritance_diagram_directive ( name , arguments , options , content , lineno , content_offset , block_text , state , state_machine ) : node = inheritance_diagram ( ) class_names = arguments graph = InheritanceGraph ( class_names ) for name in graph . get_all_class_names ( ) : refnodes , x = xfileref_role ( 'class'...
Run when the inheritance_diagram directive is first encountered .
234,031
def run_dot ( self , args , name , parts = 0 , urls = { } , graph_options = { } , node_options = { } , edge_options = { } ) : try : dot = subprocess . Popen ( [ 'dot' ] + list ( args ) , stdin = subprocess . PIPE , stdout = subprocess . PIPE , close_fds = True ) except OSError : raise DotException ( "Could not execute ...
Run graphviz dot over this graph returning whatever dot writes to stdout .
234,032
def parse_md_to_rst ( file ) : try : from m2r import parse_from_file return parse_from_file ( file ) . replace ( "artwork/" , "http://198.27.119.65/" ) except ImportError : return read ( file )
Read Markdown file and convert to ReStructured Text .
234,033
def deleted_count ( self ) : if isinstance ( self . raw_result , list ) : return len ( self . raw_result ) else : return self . raw_result
The number of documents deleted .
234,034
def generate_id ( ) : try : return unicode ( uuid1 ( ) ) . replace ( u"-" , u"" ) except NameError : return str ( uuid1 ( ) ) . replace ( u"-" , u"" )
Generate new UUID
234,035
def insert ( self , docs , * args , ** kwargs ) : if isinstance ( docs , list ) : return self . insert_many ( docs , * args , ** kwargs ) else : return self . insert_one ( docs , * args , ** kwargs )
Backwards compatibility with insert
234,036
def update ( self , query , doc , * args , ** kwargs ) : if isinstance ( doc , list ) : return [ self . update_one ( query , item , * args , ** kwargs ) for item in doc ] else : return self . update_one ( query , doc , * args , ** kwargs )
BAckwards compatibility with update
234,037
def update_one ( self , query , doc ) : if self . table is None : self . build_table ( ) if u"$set" in doc : doc = doc [ u"$set" ] allcond = self . parse_query ( query ) try : result = self . table . update ( doc , allcond ) except : result = None return UpdateResult ( raw_result = result )
Updates one element of the collection
234,038
def find ( self , filter = None , sort = None , skip = None , limit = None , * args , ** kwargs ) : if self . table is None : self . build_table ( ) if filter is None : result = self . table . all ( ) else : allcond = self . parse_query ( filter ) try : result = self . table . search ( allcond ) except ( AttributeError...
Finds all matching results
234,039
def find_one ( self , filter = None ) : if self . table is None : self . build_table ( ) allcond = self . parse_query ( filter ) return self . table . get ( allcond )
Finds one matching query element
234,040
def remove ( self , spec_or_id , multi = True , * args , ** kwargs ) : if multi : return self . delete_many ( spec_or_id ) return self . delete_one ( spec_or_id )
Backwards compatibility with remove
234,041
def delete_one ( self , query ) : item = self . find_one ( query ) result = self . table . remove ( where ( u'_id' ) == item [ u'_id' ] ) return DeleteResult ( raw_result = result )
Deletes one document from the collection
234,042
def delete_many ( self , query ) : items = self . find ( query ) result = [ self . table . remove ( where ( u'_id' ) == item [ u'_id' ] ) for item in items ] if query == { } : self . table . _last_id = 0 return DeleteResult ( raw_result = result )
Removes all items matching the mongo query
234,043
def paginate ( self , skip , limit ) : if not self . count ( ) or not limit : return skip = skip or 0 pages = int ( ceil ( self . count ( ) / float ( limit ) ) ) limits = { } last = 0 for i in range ( pages ) : current = limit * i limits [ last ] = current last = current if limit and limit < self . count ( ) : limit = ...
Paginate list of records
234,044
def should_stream ( proxy_response ) : content_type = proxy_response . headers . get ( 'Content-Type' ) if is_html_content_type ( content_type ) : return False try : content_length = int ( proxy_response . headers . get ( 'Content-Length' , 0 ) ) except ValueError : content_length = 0 if not content_length or content_l...
Function to verify if the proxy_response must be converted into a stream . This will be done by checking the proxy_response content - length and verify if its length is bigger than one stipulated by MIN_STREAMING_LENGTH .
234,045
def get_charset ( content_type ) : if not content_type : return DEFAULT_CHARSET matched = _get_charset_re . search ( content_type ) if matched : return matched . group ( 'charset' ) . replace ( '"' , '' ) return DEFAULT_CHARSET
Function used to retrieve the charset from a content - type . If there is no charset in the content type then the charset defined on DEFAULT_CHARSET will be returned
234,046
def required_header ( header ) : if header in IGNORE_HEADERS : return False if header . startswith ( 'HTTP_' ) or header == 'CONTENT_TYPE' : return True return False
Function that verify if the header parameter is a essential header
234,047
def normalize_request_headers ( request ) : r norm_headers = { } for header , value in request . META . items ( ) : if required_header ( header ) : norm_header = header . replace ( 'HTTP_' , '' ) . title ( ) . replace ( '_' , '-' ) norm_headers [ norm_header ] = value return norm_headers
r Function used to transform header replacing HTTP \ _ to and replace _ to -
234,048
def encode_items ( items ) : encoded = [ ] for key , values in items : for value in values : encoded . append ( ( key . encode ( 'utf-8' ) , value . encode ( 'utf-8' ) ) ) return encoded
Function that encode all elements in the list of items passed as a parameter
234,049
def cookie_from_string ( cookie_string , strict_cookies = False ) : if strict_cookies : cookies = SimpleCookie ( COOKIE_PREFIX + cookie_string ) if not cookies . keys ( ) : return None cookie_name , = cookies . keys ( ) cookie_dict = { k : v for k , v in cookies [ cookie_name ] . items ( ) if v and k != 'comment' } coo...
Parser for HTTP header set - cookie The return from this function will be used as parameters for django s response . set_cookie method . Because set_cookie doesn t have parameter comment this cookie attribute will be ignored .
234,050
def unquote ( value ) : if len ( value ) > 1 and value [ 0 ] == '"' and value [ - 1 ] == '"' : value = value [ 1 : - 1 ] . replace ( r'\"' , '"' ) return value
Remove wrapping quotes from a string .
234,051
def asbool ( value ) : is_string = isinstance ( value , string_types ) if is_string : value = value . strip ( ) . lower ( ) if value in ( 'true' , 'yes' , 'on' , 'y' , 't' , '1' , ) : return True elif value in ( 'false' , 'no' , 'off' , 'n' , 'f' , '0' ) : return False else : raise ValueError ( "String is not true/fals...
Function used to convert certain string values into an appropriated boolean value . If value is not a string the built - in python bool function will be used to convert the passed parameter
234,052
def should_transform ( self ) : if not HAS_DIAZO : self . log . info ( "HAS_DIAZO: false" ) return False if asbool ( self . request . META . get ( DIAZO_OFF_REQUEST_HEADER ) ) : self . log . info ( "DIAZO_OFF_REQUEST_HEADER in request.META: off" ) return False if asbool ( self . response . get ( DIAZO_OFF_RESPONSE_HEAD...
Determine if we should transform the response
234,053
def transform ( self , rules , theme_template , is_html5 , context_data = None ) : if not self . should_transform ( ) : self . log . info ( "Don't need to be transformed" ) return self . response theme = loader . render_to_string ( theme_template , context = context_data , request = self . request ) output_xslt = compi...
Method used to make a transformation on the content of the http response based on the rules and theme_templates passed as paremters
234,054
def set_html5_doctype ( self ) : doctype = b'<!DOCTYPE html>\n' content = doctype_re . subn ( doctype , self . response . content , 1 ) [ 0 ] self . response . content = content
Method used to transform a doctype in to a properly html5 doctype
234,055
def _output ( self , s ) : if s . lower ( ) . startswith ( b'host: ' ) : self . _buffer . insert ( 1 , s ) else : self . _buffer . append ( s )
Host header should always be first
234,056
def get_django_response ( proxy_response , strict_cookies = False ) : status = proxy_response . status headers = proxy_response . headers logger . debug ( 'Proxy response headers: %s' , headers ) content_type = headers . get ( 'Content-Type' ) logger . debug ( 'Content-Type: %s' , content_type ) if should_stream ( prox...
This method is used to create an appropriate response based on the Content - Length of the proxy_response . If the content is bigger than MIN_STREAMING_LENGTH which is found on utils . py than django . http . StreamingHttpResponse will be created else a django . http . HTTPResponse will be created instead
234,057
def get_request_headers ( self ) : request_headers = self . get_proxy_request_headers ( self . request ) if ( self . add_remote_user and hasattr ( self . request , 'user' ) and self . request . user . is_active ) : request_headers [ 'REMOTE_USER' ] = self . request . user . get_username ( ) self . log . info ( "REMOTE_...
Return request headers that will be sent to upstream .
234,058
def get_encoded_query_params ( self ) : get_data = encode_items ( self . request . GET . lists ( ) ) return urlencode ( get_data )
Return encoded query params to be used in proxied request
234,059
def stream_download ( url , target_path , verbose = False ) : response = requests . get ( url , stream = True ) handle = open ( target_path , "wb" ) if verbose : print ( "Beginning streaming download of %s" % url ) start = datetime . now ( ) try : content_length = int ( response . headers [ 'Content-Length' ] ) content...
Download a large file without loading it into memory .
234,060
def validate_object_id ( object_id ) : result = re . match ( OBJECT_ID_RE , str ( object_id ) ) if not result : print ( "'%s' appears not to be a valid 990 object_id" % object_id ) raise RuntimeError ( OBJECT_ID_MSG ) return object_id
It s easy to make a mistake entering these validate the format
234,061
def _get_table_start ( self ) : if self . documentation : standardized_table_start = { 'object_id' : { 'value' : self . object_id , 'ordering' : - 1 , 'line_number' : 'NA' , 'description' : 'IRS-assigned object id' , 'db_type' : 'String(18)' } , 'ein' : { 'value' : self . ein , 'ordering' : - 2 , 'line_number' : 'NA' ,...
prefill the columns we need for all tables
234,062
def debracket ( string ) : result = re . sub ( BRACKET_RE , ';' , str ( string ) ) result = result . lstrip ( ';' ) result = result . lstrip ( ' ' ) result = result . replace ( '; ;' , ';' ) return result
Eliminate the bracketed var names in doc line strings
234,063
def _set_schedules ( self ) : self . schedules = [ 'ReturnHeader990x' , ] self . otherforms = [ ] for sked in self . raw_irs_dict [ 'Return' ] [ 'ReturnData' ] . keys ( ) : if not sked . startswith ( "@" ) : if sked in KNOWN_SCHEDULES : self . schedules . append ( sked ) else : self . otherforms . append ( sked )
Attach the known and unknown schedules
234,064
def get_parsed_sked ( self , skedname ) : if not self . processed : raise Exception ( "Filing must be processed to return parsed sked" ) if skedname in self . schedules : matching_skeds = [ ] for sked in self . result : if sked [ 'schedule_name' ] == skedname : matching_skeds . append ( sked ) return matching_skeds els...
Returns an array because multiple sked K s are allowed
234,065
def headers ( self ) : client_headers = getattr ( self . client , 'headers' , { } ) return dict ( self . DEFAULT_HEADERS , ** client_headers )
Return headers of the uploader instance . This would include the headers of the client instance .
234,066
def headers_as_list ( self ) : headers = self . headers headers_list = [ '{}: {}' . format ( key , value ) for key , value in iteritems ( headers ) ] return headers_list
Does the same as headers except it is returned as a list .
234,067
def get_offset ( self ) : resp = requests . head ( self . url , headers = self . headers ) offset = resp . headers . get ( 'upload-offset' ) if offset is None : msg = 'Attempt to retrieve offset fails with status {}' . format ( resp . status_code ) raise TusCommunicationError ( msg , resp . status_code , resp . content...
Return offset from tus server .
234,068
def encode_metadata ( self ) : encoded_list = [ ] for key , value in iteritems ( self . metadata ) : key_str = str ( key ) if re . search ( r'^$|[\s,]+' , key_str ) : msg = 'Upload-metadata key "{}" cannot be empty nor contain spaces or commas.' raise ValueError ( msg . format ( key_str ) ) value_bytes = b ( value ) en...
Return list of encoded metadata as defined by the Tus protocol .
234,069
def get_url ( self ) : if self . store_url and self . url_storage : key = self . fingerprinter . get_fingerprint ( self . get_file_stream ( ) ) url = self . url_storage . get_item ( key ) if not url : url = self . create_url ( ) self . url_storage . set_item ( key , url ) return url else : return self . create_url ( )
Return the tus upload url .
234,070
def create_url ( self ) : headers = self . headers headers [ 'upload-length' ] = str ( self . file_size ) headers [ 'upload-metadata' ] = ',' . join ( self . encode_metadata ( ) ) resp = requests . post ( self . client . url , headers = headers ) url = resp . headers . get ( "location" ) if url is None : msg = 'Attempt...
Return upload url .
234,071
def request_length ( self ) : remainder = self . stop_at - self . offset return self . chunk_size if remainder > self . chunk_size else remainder
Return length of next chunk upload .
234,072
def verify_upload ( self ) : if self . request . status_code == 204 : return True else : raise TusUploadFailed ( '' , self . request . status_code , self . request . response_content )
Confirm that the last upload was sucessful . Raises TusUploadFailed exception if the upload was not sucessful .
234,073
def get_file_stream ( self ) : if self . file_stream : self . file_stream . seek ( 0 ) return self . file_stream elif os . path . isfile ( self . file_path ) : return open ( self . file_path , 'rb' ) else : raise ValueError ( "invalid file {}" . format ( self . file_path ) )
Return a file stream instance of the upload .
234,074
def file_size ( self ) : stream = self . get_file_stream ( ) stream . seek ( 0 , os . SEEK_END ) return stream . tell ( )
Return size of the file .
234,075
def upload ( self , stop_at = None ) : self . stop_at = stop_at or self . file_size while self . offset < self . stop_at : self . upload_chunk ( ) else : if self . log_func : self . log_func ( "maximum upload specified({} bytes) has been reached" . format ( self . stop_at ) )
Perform file upload .
234,076
def upload_chunk ( self ) : self . _retried = 0 self . _do_request ( ) self . offset = int ( self . request . response_headers . get ( 'upload-offset' ) ) if self . log_func : msg = '{} bytes uploaded ...' . format ( self . offset ) self . log_func ( msg )
Upload chunk of file .
234,077
def get_item ( self , key ) : result = self . _db . search ( self . _urls . key == key ) return result [ 0 ] . get ( 'url' ) if result else None
Return the tus url of a file identified by the key specified .
234,078
def set_item ( self , key , url ) : if self . _db . search ( self . _urls . key == key ) : self . _db . update ( { 'url' : url } , self . _urls . key == key ) else : self . _db . insert ( { 'key' : key , 'url' : url } )
Store the url value under the unique key .
234,079
def perform ( self ) : try : host = '{}://{}' . format ( self . _url . scheme , self . _url . netloc ) path = self . _url . geturl ( ) . replace ( host , '' , 1 ) chunk = self . file . read ( self . _content_length ) if self . _upload_checksum : self . _request_headers [ "upload-checksum" ] = " " . join ( ( self . _che...
Perform actual request .
234,080
def get_fingerprint ( self , fs ) : hasher = hashlib . md5 ( ) buf = self . _encode_data ( fs . read ( self . BLOCK_SIZE ) ) while len ( buf ) > 0 : hasher . update ( buf ) buf = fs . read ( self . BLOCK_SIZE ) return 'md5:' + hasher . hexdigest ( )
Return a unique fingerprint string value based on the file stream recevied
234,081
def init_poolmanager ( self , connections , maxsize , block = False , ** pool_kwargs ) : try : pool_kwargs [ 'ssl_version' ] = ssl . PROTOCOL_TLS except AttributeError : pool_kwargs [ 'ssl_version' ] = ssl . PROTOCOL_SSLv23 return super ( SSLAdapter , self ) . init_poolmanager ( connections , maxsize , block , ** pool_...
Called to initialize the HTTPAdapter when no proxy is used .
234,082
def proxy_manager_for ( self , proxy , ** proxy_kwargs ) : try : proxy_kwargs [ 'ssl_version' ] = ssl . PROTOCOL_TLS except AttributeError : proxy_kwargs [ 'ssl_version' ] = ssl . PROTOCOL_SSLv23 return super ( SSLAdapter , self ) . proxy_manager_for ( proxy , ** proxy_kwargs )
Called to initialize the HTTPAdapter when a proxy is used .
234,083
def make_calls ( self , num_calls = 1 ) : self . _cull ( ) while self . _outstanding_calls + num_calls > self . _max_calls_per_second : time . sleep ( 0 ) self . _cull ( ) self . _call_times . append ( self . CallRecord ( time = time . time ( ) , num_calls = num_calls ) ) self . _outstanding_calls += num_calls
Adds appropriate sleep to avoid making too many calls .
234,084
def _cull ( self ) : right_now = time . time ( ) cull_from = - 1 for index in range ( len ( self . _call_times ) ) : if right_now - self . _call_times [ index ] . time >= 1.0 : cull_from = index self . _outstanding_calls -= self . _call_times [ index ] . num_calls else : break if cull_from > - 1 : self . _call_times = ...
Remove calls more than 1 second old from the queue .
234,085
def map_with_retries ( self , requests , responses_for_requests ) : retries = [ ] response_futures = [ preq . callable ( ) for preq in requests ] for request , response_future in zip ( requests , response_futures ) : try : response = response_future . result ( ) if response is not None and response . status_code == 403...
Provides session - based retry functionality
234,086
def multi_get ( self , urls , query_params = None , to_json = True ) : return self . _multi_request ( MultiRequest . _VERB_GET , urls , query_params , data = None , to_json = to_json , )
Issue multiple GET requests .
234,087
def multi_post ( self , urls , query_params = None , data = None , to_json = True , send_as_file = False ) : return self . _multi_request ( MultiRequest . _VERB_POST , urls , query_params , data , to_json = to_json , send_as_file = send_as_file , )
Issue multiple POST requests .
234,088
def _zip_request_params ( self , urls , query_params , data ) : if not isinstance ( urls , list ) : urls = [ urls ] if not isinstance ( query_params , list ) : query_params = [ query_params ] if not isinstance ( data , list ) : data = [ data ] url_count = len ( urls ) query_param_count = len ( query_params ) data_count...
Massages inputs and returns a list of 3 - tuples zipping them up .
234,089
def _wait_for_response ( self , requests ) : failed_requests = [ ] responses_for_requests = OrderedDict . fromkeys ( requests ) for retry in range ( self . _max_retry ) : try : logging . debug ( 'Try #{0}' . format ( retry + 1 ) ) self . _availability_limiter . map_with_retries ( requests , responses_for_requests ) fai...
Issues a batch of requests and waits for the responses . If some of the requests fail it will retry the failed ones up to _max_retry times .
234,090
def _convert_to_json ( self , response ) : try : return response . json ( ) except ValueError : logging . warning ( 'Expected response in JSON format from {0} but the actual response text is: {1}' . format ( response . request . url , response . text , ) ) return None
Converts response to JSON . If the response cannot be converted to JSON then None is returned .
234,091
def _multi_request ( self , verb , urls , query_params , data , to_json = True , send_as_file = False ) : if not urls : raise InvalidRequestError ( 'No URL supplied' ) request_params = self . _zip_request_params ( urls , query_params , data ) batch_of_params = [ request_params [ pos : pos + self . _max_requests ] for p...
Issues multiple batches of simultaneous HTTP requests and waits for responses .
234,092
def error_handling ( cls , fn ) : def wrapper ( * args , ** kwargs ) : try : result = fn ( * args , ** kwargs ) return result except InvalidRequestError as e : write_exception ( e ) if hasattr ( e , 'request' ) : write_error_message ( 'request {0}' . format ( repr ( e . request ) ) ) if hasattr ( e , 'response' ) : wri...
Decorator to handle errors
234,093
def acquire_node ( self , node ) : try : return node . set ( self . resource , self . lock_key , nx = True , px = self . ttl ) except ( redis . exceptions . ConnectionError , redis . exceptions . TimeoutError ) : return False
acquire a single redis node
234,094
def release_node ( self , node ) : try : node . _release_script ( keys = [ self . resource ] , args = [ self . lock_key ] ) except ( redis . exceptions . ConnectionError , redis . exceptions . TimeoutError ) : pass
release a single redis node
234,095
def _extract_response_xml ( self , domain , response ) : attributes = { } alexa_keys = { 'POPULARITY' : 'TEXT' , 'REACH' : 'RANK' , 'RANK' : 'DELTA' } try : xml_root = ET . fromstring ( response . _content ) for xml_child in xml_root . findall ( 'SD//' ) : if xml_child . tag in alexa_keys and alexa_keys [ xml_child . t...
Extract XML content of an HTTP response into dictionary format .
234,096
def _bulk_cache_lookup ( self , api_name , keys ) : if self . _cache : responses = self . _cache . bulk_lookup ( api_name , keys ) missing_keys = [ key for key in keys if key not in responses . keys ( ) ] return ( responses , missing_keys ) return ( { } , keys )
Performes a bulk cache lookup and returns a tuple with the results found and the keys missing in the cache . If cached is not configured it will return an empty dictionary of found results and the initial list of keys .
234,097
def _write_cache_to_file ( self ) : with ( open ( self . _cache_file_name , 'w' ) ) as fp : fp . write ( simplejson . dumps ( self . _cache ) )
Write the contents of the cache to a file on disk .
234,098
def _read_cache_from_file ( self ) : cache = { } try : with ( open ( self . _cache_file_name , 'r' ) ) as fp : contents = fp . read ( ) cache = simplejson . loads ( contents ) except ( IOError , JSONDecodeError ) : pass return cache
Read the contents of the cache from a file on disk .
234,099
def bulk_lookup ( self , api_name , keys ) : cached_data = { } for key in keys : value = self . lookup_value ( api_name , key ) if value is not None : cached_data [ key ] = value return cached_data
Perform lookup on an enumerable of keys .