idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
8,700 | def askopenfile ( mode = "r" , ** options ) : "Ask for a filename to open, and returned the opened file" filename = askopenfilename ( ** options ) if filename : return open ( filename , mode ) return None | Ask for a filename to open and returned the opened file |
8,701 | def askopenfiles ( mode = "r" , ** options ) : files = askopenfilenames ( ** options ) if files : ofiles = [ ] for filename in files : ofiles . append ( open ( filename , mode ) ) files = ofiles return files | Ask for multiple filenames and return the open file objects |
8,702 | def asksaveasfile ( mode = "w" , ** options ) : "Ask for a filename to save as, and returned the opened file" filename = asksaveasfilename ( ** options ) if filename : return open ( filename , mode ) return None | Ask for a filename to save as and returned the opened file |
8,703 | def spaced_coordinate ( name , keys , ordered = True ) : def validate ( self ) : if set ( keys ) != set ( self ) : raise ValueError ( '{} needs keys {} and got {}' . format ( type ( self ) . __name__ , keys , tuple ( self ) ) ) new_class = type ( name , ( Coordinate , ) , { 'default_order' : keys if ordered else None ,... | Create a subclass of Coordinate instances of which must have exactly the given keys . |
8,704 | def norm ( self , order = 2 ) : return ( sum ( val ** order for val in abs ( self ) . values ( ) ) ) ** ( 1 / order ) | Find the vector norm with the given order of the values |
8,705 | def jsonify ( o , max_depth = - 1 , parse_enums = PARSE_KEEP ) : if max_depth == 0 : return o max_depth -= 1 if isinstance ( o , dict ) : keyattrs = getattr ( o . __class__ , '_altnames' , { } ) def _getter ( key , value ) : key = keyattrs . get ( key , key ) other = getattr ( o , key , value ) if callable ( other ) : ... | Walks through object o and attempts to get the property instead of the key if available . This means that for our VDev objects we can easily get a dict of all the parsed values . |
8,706 | def copy_files ( self ) : files = [ u'LICENSE' , u'CONTRIBUTING.rst' ] this_dir = dirname ( abspath ( __file__ ) ) for _file in files : sh . cp ( '{0}/templates/{1}' . format ( this_dir , _file ) , '{0}/' . format ( self . book . local_path ) ) if self . book . meta . rdf_path : sh . cp ( self . book . meta . rdf_path ... | Copy the LICENSE and CONTRIBUTING files to each folder repo Generate covers if needed . Dump the metadata . |
8,707 | def _collate_data ( collation , first_axis , second_axis ) : if first_axis not in collation : collation [ first_axis ] = { } collation [ first_axis ] [ "create" ] = 0 collation [ first_axis ] [ "modify" ] = 0 collation [ first_axis ] [ "delete" ] = 0 first = collation [ first_axis ] first [ second_axis ] = first [ seco... | Collects information about the number of edit actions belonging to keys in a supplied dictionary of object or changeset ids . |
8,708 | def extract_changesets ( objects ) : def add_changeset_info ( collation , axis , item ) : if axis not in collation : collation [ axis ] = { } first = collation [ axis ] first [ "id" ] = axis first [ "username" ] = item [ "username" ] first [ "uid" ] = item [ "uid" ] first [ "timestamp" ] = item [ "timestamp" ] collatio... | Provides information about each changeset present in an OpenStreetMap diff file . |
8,709 | def to_str ( obj ) : if isinstance ( obj , str ) : return obj if isinstance ( obj , unicode ) : return obj . encode ( 'utf-8' ) return str ( obj ) | convert a object to string |
8,710 | def get_managed_zone ( self , zone ) : if zone . endswith ( '.in-addr.arpa.' ) : return self . reverse_prefix + '-' . join ( zone . split ( '.' ) [ - 5 : - 3 ] ) return self . forward_prefix + '-' . join ( zone . split ( '.' ) [ : - 1 ] ) | Get the GDNS managed zone name for a DNS zone . |
8,711 | async def get_records_for_zone ( self , dns_zone , params = None ) : managed_zone = self . get_managed_zone ( dns_zone ) url = f'{self._base_url}/managedZones/{managed_zone}/rrsets' if not params : params = { } if 'fields' not in params : params [ 'fields' ] = ( 'rrsets/name,rrsets/kind,rrsets/rrdatas,' 'rrsets/type,rr... | Get all resource record sets for a managed zone using the DNS zone . |
8,712 | async def is_change_done ( self , zone , change_id ) : zone_id = self . get_managed_zone ( zone ) url = f'{self._base_url}/managedZones/{zone_id}/changes/{change_id}' resp = await self . get_json ( url ) return resp [ 'status' ] == self . DNS_CHANGES_DONE | Check if a DNS change has completed . |
8,713 | async def publish_changes ( self , zone , changes ) : zone_id = self . get_managed_zone ( zone ) url = f'{self._base_url}/managedZones/{zone_id}/changes' resp = await self . request ( 'post' , url , json = changes ) return json . loads ( resp ) [ 'id' ] | Post changes to a zone . |
8,714 | def leave ( self , reason = None , message = None ) : return self . _async_session . leave ( reason = reason , log_message = message ) | Actively close this WAMP session . |
8,715 | def call ( self , procedure , * args , ** kwargs ) : return self . _async_session . call ( procedure , * args , ** kwargs ) | Call a remote procedure . |
8,716 | def register ( self , endpoint , procedure = None , options = None ) : def proxy_endpoint ( * args , ** kwargs ) : return self . _callbacks_runner . put ( partial ( endpoint , * args , ** kwargs ) ) return self . _async_session . register ( proxy_endpoint , procedure = procedure , options = options ) | Register a procedure for remote calling . |
8,717 | def publish ( self , topic , * args , ** kwargs ) : return self . _async_session . publish ( topic , * args , ** kwargs ) | Publish an event to a topic . |
8,718 | def subscribe ( self , handler , topic = None , options = None ) : def proxy_handler ( * args , ** kwargs ) : return self . _callbacks_runner . put ( partial ( handler , * args , ** kwargs ) ) return self . _async_session . subscribe ( proxy_handler , topic = topic , options = options ) | Subscribe to a topic for receiving events . |
8,719 | def b58encode ( val , charset = DEFAULT_CHARSET ) : def _b58encode_int ( int_ , default = bytes ( [ charset [ 0 ] ] ) ) : if not int_ and default : return default output = b'' while int_ : int_ , idx = divmod ( int_ , base ) output = charset [ idx : idx + 1 ] + output return output if not isinstance ( val , bytes ) : r... | Encode input to base58check encoding . |
8,720 | def b58decode ( val , charset = DEFAULT_CHARSET ) : def _b58decode_int ( val ) : output = 0 for char in val : output = output * base + charset . index ( char ) return output if isinstance ( val , str ) : val = val . encode ( ) if isinstance ( charset , str ) : charset = charset . encode ( ) base = len ( charset ) if no... | Decode base58check encoded input to original raw bytes . |
8,721 | def wait_for_edge ( self ) : GPIO . remove_event_detect ( self . _pin ) GPIO . wait_for_edge ( self . _pin , self . _edge ) | This will remove remove any callbacks you might have specified |
8,722 | def request_finished_callback ( sender , ** kwargs ) : logger = logging . getLogger ( __name__ ) level = settings . AUTOMATED_LOGGING [ 'loglevel' ] [ 'request' ] user = get_current_user ( ) uri , application , method , status = get_current_environ ( ) excludes = settings . AUTOMATED_LOGGING [ 'exclude' ] [ 'request' ]... | This function logs if the user acceses the page |
8,723 | def request_exception ( sender , request , ** kwargs ) : if not isinstance ( request , WSGIRequest ) : logger = logging . getLogger ( __name__ ) level = CRITICAL if request . status_code <= 500 else WARNING logger . log ( level , '%s exception occured (%s)' , request . status_code , request . reason_phrase ) else : log... | Automated request exception logging . |
8,724 | def source_start ( base = '' , book_id = 'book' ) : repo_htm_path = "{book_id}-h/{book_id}-h.htm" . format ( book_id = book_id ) possible_paths = [ "book.asciidoc" , repo_htm_path , "{}-0.txt" . format ( book_id ) , "{}-8.txt" . format ( book_id ) , "{}.txt" . format ( book_id ) , "{}-pdf.pdf" . format ( book_id ) , ] ... | chooses a starting source file in the base directory for id = book_id |
8,725 | def pretty_dump ( fn ) : @ wraps ( fn ) def pretty_dump_wrapper ( * args , ** kwargs ) : response . content_type = "application/json; charset=utf-8" return json . dumps ( fn ( * args , ** kwargs ) , indent = 4 , separators = ( ',' , ': ' ) ) return pretty_dump_wrapper | Decorator used to output prettified JSON . |
8,726 | def decode_json_body ( ) : raw_data = request . body . read ( ) try : return json . loads ( raw_data ) except ValueError as e : raise HTTPError ( 400 , e . __str__ ( ) ) | Decode bottle . request . body to JSON . |
8,727 | def handle_type_error ( fn ) : @ wraps ( fn ) def handle_type_error_wrapper ( * args , ** kwargs ) : def any_match ( string_list , obj ) : return filter ( lambda x : x in obj , string_list ) try : return fn ( * args , ** kwargs ) except TypeError as e : message = e . __str__ ( ) str_list = [ "takes exactly" , "got an u... | Convert TypeError to bottle . HTTPError with 400 code and message about wrong parameters . |
8,728 | def json_to_params ( fn = None , return_json = True ) : def json_to_params_decorator ( fn ) : @ handle_type_error @ wraps ( fn ) def json_to_params_wrapper ( * args , ** kwargs ) : data = decode_json_body ( ) if type ( data ) in [ tuple , list ] : args = list ( args ) + data elif type ( data ) == dict : allowed_keys = ... | Convert JSON in the body of the request to the parameters for the wrapped function . |
8,729 | def json_to_data ( fn = None , return_json = True ) : def json_to_data_decorator ( fn ) : @ handle_type_error @ wraps ( fn ) def get_data_wrapper ( * args , ** kwargs ) : kwargs [ "data" ] = decode_json_body ( ) if not return_json : return fn ( * args , ** kwargs ) return encode_json_body ( fn ( * args , ** kwargs ) ) ... | Decode JSON from the request and add it as data parameter for wrapped function . |
8,730 | def form_to_params ( fn = None , return_json = True ) : def forms_to_params_decorator ( fn ) : @ handle_type_error @ wraps ( fn ) def forms_to_params_wrapper ( * args , ** kwargs ) : kwargs . update ( dict ( request . forms ) ) if not return_json : return fn ( * args , ** kwargs ) return encode_json_body ( fn ( * args ... | Convert bottle forms request to parameters for the wrapped function . |
8,731 | def fetch ( sequence , time = 'hour' ) : import StringIO import gzip import requests if time not in [ 'minute' , 'hour' , 'day' ] : raise ValueError ( 'The supplied type of replication file does not exist.' ) sqn = str ( sequence ) . zfill ( 9 ) url = "https://planet.osm.org/replication/%s/%s/%s/%s.osc.gz" % ( time , s... | Fetch an OpenStreetMap diff file . |
8,732 | def m2m_callback ( sender , instance , action , reverse , model , pk_set , using , ** kwargs ) : if validate_instance ( instance ) and settings . AUTOMATED_LOGGING [ 'to_database' ] : if action in [ "post_add" , 'post_remove' ] : modification = [ model . objects . get ( pk = x ) for x in pk_set ] if 'al_chl' in instanc... | Many 2 Many relationship signall receivver . |
8,733 | def font ( self , name , properties ) : size , slant , weight = ( properties ) return ( name , ( self . ty ( size ) , slant , weight ) ) | Return a tuple that contains font properties required for rendering . |
8,734 | def async_update ( self ) : _LOGGER . debug ( 'Calling update on Alarm.com' ) response = None if not self . _login_info : yield from self . async_login ( ) try : with async_timeout . timeout ( 10 , loop = self . _loop ) : response = yield from self . _websession . get ( self . ALARMDOTCOM_URL + '{}/main.aspx' . format ... | Fetch the latest state . |
8,735 | def create_api_handler ( self ) : try : self . github = github3 . login ( username = config . data [ 'gh_user' ] , password = config . data [ 'gh_password' ] ) except KeyError as e : raise config . NotConfigured ( e ) logger . info ( "ratelimit remaining: {}" . format ( self . github . ratelimit_remaining ) ) if hasatt... | Creates an api handler and sets it on self |
8,736 | def _validate_func_args ( func , kwargs ) : args , varargs , varkw , defaults = inspect . getargspec ( func ) if set ( kwargs . keys ( ) ) != set ( args [ 1 : ] ) : raise TypeError ( "decorator kwargs do not match %s()'s kwargs" % func . __name__ ) | Validate decorator args when used to decorate a function . |
8,737 | def enclosing_frame ( frame = None , level = 2 ) : frame = frame or sys . _getframe ( level ) while frame . f_globals . get ( '__name__' ) == __name__ : frame = frame . f_back return frame | Get an enclosing frame that skips decorator code |
8,738 | def get_event_consumer ( config , success_channel , error_channel , metrics , ** kwargs ) : builder = event_consumer . GPSEventConsumerBuilder ( config , success_channel , error_channel , metrics , ** kwargs ) return builder . build_event_consumer ( ) | Get a GPSEventConsumer client . |
8,739 | def get_enricher ( config , metrics , ** kwargs ) : builder = enricher . GCEEnricherBuilder ( config , metrics , ** kwargs ) return builder . build_enricher ( ) | Get a GCEEnricher client . |
8,740 | def get_gdns_publisher ( config , metrics , ** kwargs ) : builder = gdns_publisher . GDNSPublisherBuilder ( config , metrics , ** kwargs ) return builder . build_publisher ( ) | Get a GDNSPublisher client . |
8,741 | def normalize_allele_name ( raw_allele , omit_dra1 = False , infer_class2_pair = True ) : cache_key = ( raw_allele , omit_dra1 , infer_class2_pair ) if cache_key in _normalized_allele_cache : return _normalized_allele_cache [ cache_key ] parsed_alleles = parse_classi_or_classii_allele_name ( raw_allele , infer_pair = i... | MHC alleles are named with a frustratingly loose system . It s not uncommon to see dozens of different forms for the same allele . |
8,742 | def getVersion ( data ) : data = data . splitlines ( ) return next ( ( v for v , u in zip ( data , data [ 1 : ] ) if len ( v ) == len ( u ) and allSame ( u ) and hasDigit ( v ) and "." in v ) ) | Parse version from changelog written in RST format . |
8,743 | def split_species_prefix ( name , seps = "-:_ " ) : species = None name_upper = name . upper ( ) name_len = len ( name ) for curr_prefix in _all_prefixes : n = len ( curr_prefix ) if name_len <= n : continue if name_upper . startswith ( curr_prefix . upper ( ) ) : species = curr_prefix name = name [ n : ] . strip ( sep... | Splits off the species component of the allele name from the rest of it . |
8,744 | def formatFlow ( s ) : result = "" shifts = [ ] pos = 0 nextIsList = False def IsNextList ( index , maxIndex , buf ) : if index == maxIndex : return False if buf [ index + 1 ] == '<' : return True if index < maxIndex - 1 : if buf [ index + 1 ] == '\n' and buf [ index + 2 ] == '<' : return True return False maxIndex = l... | Reformats the control flow output |
8,745 | def train ( self , training_set , iterations = 500 ) : if len ( training_set ) > 2 : self . __X = np . matrix ( [ example [ 0 ] for example in training_set ] ) if self . __num_labels == 1 : self . __y = np . matrix ( [ example [ 1 ] for example in training_set ] ) . reshape ( ( - 1 , 1 ) ) else : eye = np . eye ( self ... | Trains itself using the sequence data . |
8,746 | def predict ( self , X ) : return self . __cost ( self . __unroll ( self . __thetas ) , 0 , np . matrix ( X ) ) | Returns predictions of input test cases . |
8,747 | def __cost ( self , params , phase , X ) : params = self . __roll ( params ) a = np . concatenate ( ( np . ones ( ( X . shape [ 0 ] , 1 ) ) , X ) , axis = 1 ) calculated_a = [ a ] calculated_z = [ 0 ] for i , theta in enumerate ( params ) : z = calculated_a [ - 1 ] * theta . transpose ( ) calculated_z . append ( z ) a ... | Computes activation cost function and derivative . |
8,748 | def __roll ( self , unrolled ) : rolled = [ ] index = 0 for count in range ( len ( self . __sizes ) - 1 ) : in_size = self . __sizes [ count ] out_size = self . __sizes [ count + 1 ] theta_unrolled = np . matrix ( unrolled [ index : index + ( in_size + 1 ) * out_size ] ) theta_rolled = theta_unrolled . reshape ( ( out_... | Converts parameter array back into matrices . |
8,749 | def __unroll ( self , rolled ) : return np . array ( np . concatenate ( [ matrix . flatten ( ) for matrix in rolled ] , axis = 1 ) ) . reshape ( - 1 ) | Converts parameter matrices into an array . |
8,750 | def sigmoid_grad ( self , z ) : return np . multiply ( self . sigmoid ( z ) , 1 - self . sigmoid ( z ) ) | Gradient of sigmoid function . |
8,751 | def grad ( self , params , epsilon = 0.0001 ) : grad = [ ] for x in range ( len ( params ) ) : temp = np . copy ( params ) temp [ x ] += epsilon temp2 = np . copy ( params ) temp2 [ x ] -= epsilon grad . append ( ( self . __cost_function ( temp ) - self . __cost_function ( temp2 ) ) / ( 2 * epsilon ) ) return np . arra... | Used to check gradient estimation through slope approximation . |
8,752 | def postWebhook ( self , dev_id , external_id , url , event_types ) : path = 'notification/webhook' payload = { 'device' : { 'id' : dev_id } , 'externalId' : external_id , 'url' : url , 'eventTypes' : event_types } return self . rachio . post ( path , payload ) | Add a webhook to a device . |
8,753 | def putWebhook ( self , hook_id , external_id , url , event_types ) : path = 'notification/webhook' payload = { 'id' : hook_id , 'externalId' : external_id , 'url' : url , 'eventTypes' : event_types } return self . rachio . put ( path , payload ) | Update a webhook . |
8,754 | def deleteWebhook ( self , hook_id ) : path = '/' . join ( [ 'notification' , 'webhook' , hook_id ] ) return self . rachio . delete ( path ) | Remove a webhook . |
8,755 | def get ( self , hook_id ) : path = '/' . join ( [ 'notification' , 'webhook' , hook_id ] ) return self . rachio . get ( path ) | Get a webhook . |
8,756 | def connect ( self ) : self . con = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) self . con . connect ( ( self . ip , self . port ) ) log . debug ( 'Connected with set-top box at %s:%s.' , self . ip , self . port ) | Connect sets up the connection with the Horizon box . |
8,757 | def disconnect ( self ) : if self . con is not None : self . con . close ( ) log . debug ( 'Closed connection with with set-top box at %s:%s.' , self . ip , self . port ) | Disconnect closes the connection to the Horizon box . |
8,758 | def authorize ( self ) : version = self . con . makefile ( ) . readline ( ) self . con . send ( version . encode ( ) ) self . con . recv ( 2 ) self . con . send ( struct . pack ( '>B' , 1 ) ) msg = self . con . recv ( 4 ) response = struct . unpack ( ">I" , msg ) if response [ 0 ] != 0 : log . debug ( "Failed to author... | Use the magic of a unicorn and summon the set - top box to listen to us . |
8,759 | def send_key ( self , key ) : cmd = struct . pack ( ">BBBBBBH" , 4 , 1 , 0 , 0 , 0 , 0 , key ) self . con . send ( cmd ) cmd = struct . pack ( ">BBBBBBH" , 4 , 0 , 0 , 0 , 0 , 0 , key ) self . con . send ( cmd ) | Send a key to the Horizon box . |
8,760 | def is_powered_on ( self ) : host = '{0}:62137' . format ( self . ip ) try : HTTPConnection ( host , timeout = 2 ) . request ( 'GET' , '/DeviceDescription.xml' ) except ( ConnectionRefusedError , socket . timeout ) : log . debug ( 'Set-top box at %s:%s is powered off.' , self . ip , self . port ) return False log . deb... | Get power status of device . |
8,761 | def power_on ( self ) : if not self . is_powered_on ( ) : log . debug ( 'Powering on set-top box at %s:%s.' , self . ip , self . port ) self . send_key ( keys . POWER ) | Power on the set - top box . |
8,762 | def select_channel ( self , channel ) : for i in str ( channel ) : key = int ( i ) + 0xe300 self . send_key ( key ) | Select a channel . |
8,763 | def get_hmac ( message ) : key = current_app . config [ 'WEBHOOKS_SECRET_KEY' ] hmac_value = hmac . new ( key . encode ( 'utf-8' ) if hasattr ( key , 'encode' ) else key , message . encode ( 'utf-8' ) if hasattr ( message , 'encode' ) else message , sha1 ) . hexdigest ( ) return hmac_value | Calculate HMAC value of message using WEBHOOKS_SECRET_KEY . |
8,764 | def check_x_hub_signature ( signature , message ) : hmac_value = get_hmac ( message ) if hmac_value == signature or ( signature . find ( '=' ) > - 1 and hmac_value == signature [ signature . find ( '=' ) + 1 : ] ) : return True return False | Check X - Hub - Signature used by GitHub to sign requests . |
8,765 | async def list_all_active_projects ( self , page_size = 1000 ) : url = f'{self.BASE_URL}/{self.api_version}/projects' params = { 'pageSize' : page_size } responses = await self . list_all ( url , params ) projects = self . _parse_rsps_for_projects ( responses ) return [ project for project in projects if project . get ... | Get all active projects . |
8,766 | def install ( self , binder , module ) : ModuleAdapter ( module , self . _injector ) . configure ( binder ) | Add another module s bindings to a binder . |
8,767 | def expose ( self , binder , interface , annotation = None ) : private_module = self class Provider ( object ) : def get ( self ) : return private_module . private_injector . get_instance ( interface , annotation ) self . original_binder . bind ( interface , annotated_with = annotation , to_provider = Provider ) | Expose the child injector to the parent inject for a binding . |
8,768 | def _call_validators ( self ) : msg = [ ] msg . extend ( self . _validate_keyfile ( ) ) msg . extend ( self . _validate_dns_zone ( ) ) msg . extend ( self . _validate_retries ( ) ) msg . extend ( self . _validate_project ( ) ) return msg | Actually run all the validations . |
8,769 | def parse_rdf ( self ) : try : self . metadata = pg_rdf_to_json ( self . rdf_path ) except IOError as e : raise NoRDFError ( e ) if not self . authnames ( ) : self . author = '' elif len ( self . authnames ( ) ) == 1 : self . author = self . authnames ( ) [ 0 ] else : self . author = "Various" | Parses the relevant PG rdf file |
8,770 | def download_rdf ( self , force = False ) : if self . downloading : return True if not force and ( os . path . exists ( RDF_PATH ) and ( time . time ( ) - os . path . getmtime ( RDF_PATH ) ) < RDF_MAX_AGE ) : return False self . downloading = True logging . info ( 'Re-downloading RDF library from %s' % RDF_URL ) try : ... | Ensures a fresh - enough RDF file is downloaded and extracted . |
8,771 | def run ( self , url = DEFAULT_AUTOBAHN_ROUTER , realm = DEFAULT_AUTOBAHN_REALM , authmethods = None , authid = None , authrole = None , authextra = None , blocking = False , callback = None , ** kwargs ) : _init_crochet ( in_twisted = False ) self . _bootstrap ( blocking , url = url , realm = realm , authmethods = aut... | Start the background twisted thread and create the WAMP connection |
8,772 | def stop ( self ) : if not self . _started : raise NotRunningError ( "This AutobahnSync instance is not started" ) self . _callbacks_runner . stop ( ) self . _started = False | Terminate the WAMP session |
8,773 | def process_event ( self , event_id ) : with db . session . begin_nested ( ) : event = Event . query . get ( event_id ) event . _celery_task = self event . receiver . run ( event ) flag_modified ( event , 'response' ) flag_modified ( event , 'response_headers' ) db . session . add ( event ) db . session . commit ( ) | Process event in Celery . |
8,774 | def _json_column ( ** kwargs ) : return db . Column ( JSONType ( ) . with_variant ( postgresql . JSON ( none_as_null = True ) , 'postgresql' , ) , nullable = True , ** kwargs ) | Return JSON column . |
8,775 | def delete ( self , event ) : assert self . receiver_id == event . receiver_id event . response = { 'status' : 410 , 'message' : 'Gone.' } event . response_code = 410 | Mark event as deleted . |
8,776 | def get_hook_url ( self , access_token ) : if ( current_app . debug or current_app . testing ) and current_app . config . get ( 'WEBHOOKS_DEBUG_RECEIVER_URLS' , None ) : url_pattern = current_app . config [ 'WEBHOOKS_DEBUG_RECEIVER_URLS' ] . get ( self . receiver_id , None ) if url_pattern : return url_pattern % dict (... | Get URL for webhook . |
8,777 | def check_signature ( self ) : if not self . signature : return True signature_value = request . headers . get ( self . signature , None ) if signature_value : validator = 'check_' + re . sub ( r'[-]' , '_' , self . signature ) . lower ( ) check_signature = getattr ( signatures , validator ) if check_signature ( signat... | Check signature of signed request . |
8,778 | def extract_payload ( self ) : if not self . check_signature ( ) : raise InvalidSignature ( 'Invalid Signature' ) if request . is_json : delete_cached_json_for ( request ) return request . get_json ( silent = False , cache = False ) elif request . content_type == 'application/x-www-form-urlencoded' : return dict ( requ... | Extract payload from request . |
8,779 | def delete ( self , event ) : super ( CeleryReceiver , self ) . delete ( event ) AsyncResult ( event . id ) . revoke ( terminate = True ) | Abort running task if it exists . |
8,780 | def validate_receiver ( self , key , value ) : if value not in current_webhooks . receivers : raise ReceiverDoesNotExist ( self . receiver_id ) return value | Validate receiver identifier . |
8,781 | def create ( cls , receiver_id , user_id = None ) : event = cls ( id = uuid . uuid4 ( ) , receiver_id = receiver_id , user_id = user_id ) event . payload = event . receiver . extract_payload ( ) return event | Create an event instance . |
8,782 | def receiver ( self ) : try : return current_webhooks . receivers [ self . receiver_id ] except KeyError : raise ReceiverDoesNotExist ( self . receiver_id ) | Return registered receiver . |
8,783 | def receiver ( self , value ) : assert isinstance ( value , Receiver ) self . receiver_id = value . receiver_id | Set receiver instance . |
8,784 | def process ( self ) : try : self . receiver ( self ) except Exception as e : current_app . logger . exception ( 'Could not process event.' ) self . response_code = 500 self . response = dict ( status = 500 , message = str ( e ) ) return self | Process current event . |
8,785 | def register_bootstrap_functions ( ) : global _registered if _registered : return _registered = True from wrapt import discover_post_import_hooks for name in os . environ . get ( 'AUTOWRAPT_BOOTSTRAP' , '' ) . split ( ',' ) : discover_post_import_hooks ( name ) | Discover and register all post import hooks named in the AUTOWRAPT_BOOTSTRAP environment variable . The value of the environment variable must be a comma separated list . |
8,786 | def bootstrap ( ) : global _patched if _patched : return _patched = True site . execsitecustomize = _execsitecustomize_wrapper ( site . execsitecustomize ) site . execusercustomize = _execusercustomize_wrapper ( site . execusercustomize ) | Patches the site module such that the bootstrap functions for registering the post import hook callback functions are called as the last thing done when initialising the Python interpreter . This function would normally be called from the special . pth file . |
8,787 | def get_rules ( license ) : can = [ ] cannot = [ ] must = [ ] req = requests . get ( "{base_url}/licenses/{license}" . format ( base_url = BASE_URL , license = license ) , headers = _HEADERS ) if req . status_code == requests . codes . ok : data = req . json ( ) can = data [ "permitted" ] cannot = data [ "forbidden" ] ... | Gets can cannot and must rules from github license API |
8,788 | def main ( ) : all_summary = { } for license in RESOURCES : req = requests . get ( RESOURCES [ license ] ) if req . status_code == requests . codes . ok : summary = get_summary ( req . text ) can , cannot , must = get_rules ( license ) all_summary [ license ] = { "summary" : summary , "source" : RESOURCES [ license ] ,... | Gets all the license information and stores it in json format |
8,789 | def get_arguments ( ) : parser = argparse . ArgumentParser ( description = 'Handles bumping of the artifact version' ) parser . add_argument ( '--log-config' , '-l' , action = 'store' , dest = 'logger_config' , help = 'The location of the logging config json file' , default = '' ) parser . add_argument ( '--log-level' ... | This get us the cli arguments . |
8,790 | def setup_logging ( args ) : handler = logging . StreamHandler ( ) handler . setLevel ( args . log_level ) formatter = logging . Formatter ( ( '%(asctime)s - ' '%(name)s - ' '%(levelname)s - ' '%(message)s' ) ) handler . setFormatter ( formatter ) LOGGER . addHandler ( handler ) | This sets up the logging . |
8,791 | def make_response ( event ) : code , message = event . status response = jsonify ( ** event . response ) response . headers [ 'X-Hub-Event' ] = event . receiver_id response . headers [ 'X-Hub-Delivery' ] = event . id if message : response . headers [ 'X-Hub-Info' ] = message add_link_header ( response , { 'self' : url_... | Make a response from webhook event . |
8,792 | def error_handler ( f ) : @ wraps ( f ) def inner ( * args , ** kwargs ) : try : return f ( * args , ** kwargs ) except ReceiverDoesNotExist : return jsonify ( status = 404 , description = 'Receiver does not exists.' ) , 404 except InvalidPayload as e : return jsonify ( status = 415 , description = 'Receiver does not s... | Return a json payload and appropriate status code on expection . |
8,793 | def post ( self , receiver_id = None ) : try : user_id = request . oauth . access_token . user_id except AttributeError : user_id = current_user . get_id ( ) event = Event . create ( receiver_id = receiver_id , user_id = user_id ) db . session . add ( event ) db . session . commit ( ) event . process ( ) db . session .... | Handle POST request . |
8,794 | def _get_event ( receiver_id , event_id ) : event = Event . query . filter_by ( receiver_id = receiver_id , id = event_id ) . first_or_404 ( ) try : user_id = request . oauth . access_token . user_id except AttributeError : user_id = current_user . get_id ( ) if event . user_id != int ( user_id ) : abort ( 401 ) return... | Find event and check access rights . |
8,795 | def get ( self , receiver_id = None , event_id = None ) : event = self . _get_event ( receiver_id , event_id ) return make_response ( event ) | Handle GET request . |
8,796 | def delete ( self , receiver_id = None , event_id = None ) : event = self . _get_event ( receiver_id , event_id ) event . delete ( ) db . session . commit ( ) return make_response ( event ) | Handle DELETE request . |
8,797 | def _stripslashes ( s ) : r = re . sub ( r"\\(n|r)" , "\n" , s ) r = re . sub ( r"\\" , "" , r ) return r | Removes trailing and leading backslashes from string |
8,798 | def _get_config_name ( ) : p = subprocess . Popen ( 'git config --get user.name' , shell = True , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) output = p . stdout . readlines ( ) return _stripslashes ( output [ 0 ] ) | Get git config user name |
8,799 | def _get_licences ( ) : licenses = _LICENSES for license in licenses : print ( "{license_name} [{license_code}]" . format ( license_name = licenses [ license ] , license_code = license ) ) | Lists all the licenses on command line |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.