idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
8,700
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 ( * arg...
Convert bottle forms request to parameters for the wrapped function .
156
12
8,701
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 .
187
9
8,702
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 instan...
Many 2 Many relationship signall receivver .
492
10
8,703
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 .
38
11
8,704
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 .
413
6
8,705
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
200
10
8,706
def _validate_func_args ( func , kwargs ) : args , varargs , varkw , defaults = inspect . getargspec ( func ) if set ( kwargs . keys ( ) ) != set ( args [ 1 : ] ) : # chop off self raise TypeError ( "decorator kwargs do not match %s()'s kwargs" % func . __name__ )
Validate decorator args when used to decorate a function .
90
13
8,707
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
58
11
8,708
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 .
65
7
8,709
def get_enricher ( config , metrics , * * kwargs ) : builder = enricher . GCEEnricherBuilder ( config , metrics , * * kwargs ) return builder . build_enricher ( )
Get a GCEEnricher client .
51
9
8,710
def get_gdns_publisher ( config , metrics , * * kwargs ) : builder = gdns_publisher . GDNSPublisherBuilder ( config , metrics , * * kwargs ) return builder . build_publisher ( )
Get a GDNSPublisher client .
55
9
8,711
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 .
382
28
8,712
def getVersion ( data ) : data = data . splitlines ( ) return next ( ( v for v , u in zip ( data , data [ 1 : ] ) # v = version, u = underline if len ( v ) == len ( u ) and allSame ( u ) and hasDigit ( v ) and "." in v ) )
Parse version from changelog written in RST format .
74
13
8,713
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 .
112
16
8,714
def formatFlow ( s ) : result = "" shifts = [ ] # positions of opening '<' pos = 0 # symbol position in a line 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 [ ind...
Reformats the control flow output
293
7
8,715
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 .
485
8
8,716
def predict ( self , X ) : return self . __cost ( self . __unroll ( self . __thetas ) , 0 , np . matrix ( X ) )
Returns predictions of input test cases .
37
7
8,717
def __cost ( self , params , phase , X ) : params = self . __roll ( params ) a = np . concatenate ( ( np . ones ( ( X . shape [ 0 ] , 1 ) ) , X ) , axis = 1 ) # This is a1 calculated_a = [ a ] # a1 is at index 0, a_n is at index n-1 calculated_z = [ 0 ] # There is no z1, z_n is at index n-1 for i , theta in enumerate (...
Computes activation cost function and derivative .
826
8
8,718
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 .
140
9
8,719
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 .
46
9
8,720
def sigmoid_grad ( self , z ) : return np . multiply ( self . sigmoid ( z ) , 1 - self . sigmoid ( z ) )
Gradient of sigmoid function .
37
8
8,721
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 .
107
9
8,722
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 .
85
8
8,723
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 .
79
5
8,724
def deleteWebhook ( self , hook_id ) : path = '/' . join ( [ 'notification' , 'webhook' , hook_id ] ) return self . rachio . delete ( path )
Remove a webhook .
46
5
8,725
def get ( self , hook_id ) : path = '/' . join ( [ 'notification' , 'webhook' , hook_id ] ) return self . rachio . get ( path )
Get a webhook .
44
5
8,726
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 .
73
10
8,727
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 .
51
10
8,728
def authorize ( self ) : # Read the version of the set-top box and write it back. Why? I've no # idea. version = self . con . makefile ( ) . readline ( ) self . con . send ( version . encode ( ) ) # The set-top box returns with 2 bytes. I've no idea what they mean. self . con . recv ( 2 ) # The following reads and writ...
Use the magic of a unicorn and summon the set - top box to listen to us .
252
18
8,729
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 .
82
8
8,730
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 .
123
6
8,731
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 .
58
8
8,732
def select_channel ( self , channel ) : for i in str ( channel ) : key = int ( i ) + 0xe300 self . send_key ( key )
Select a channel .
36
4
8,733
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 .
103
20
8,734
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 .
71
13
8,735
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 .
113
5
8,736
def install ( self , binder , module ) : ModuleAdapter ( module , self . _injector ) . configure ( binder )
Add another module s bindings to a binder .
29
10
8,737
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 .
76
14
8,738
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 .
77
7
8,739
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
95
9
8,740
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 .
294
15
8,741
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 = au...
Start the background twisted thread and create the WAMP connection
155
11
8,742
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
46
6
8,743
def process_event ( self , event_id ) : with db . session . begin_nested ( ) : event = Event . query . get ( event_id ) event . _celery_task = self # internal binding to a Celery task event . receiver . run ( event ) # call run directly to avoid circular calls flag_modified ( event , 'response' ) flag_modified ( event ...
Process event in Celery .
106
6
8,744
def _json_column ( * * kwargs ) : return db . Column ( JSONType ( ) . with_variant ( postgresql . JSON ( none_as_null = True ) , 'postgresql' , ) , nullable = True , * * kwargs )
Return JSON column .
62
4
8,745
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 .
47
5
8,746
def get_hook_url ( self , access_token ) : # Allow overwriting hook URL in debug mode. 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 ) ...
Get URL for webhook .
166
6
8,747
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 .
100
6
8,748
def extract_payload ( self ) : if not self . check_signature ( ) : raise InvalidSignature ( 'Invalid Signature' ) if request . is_json : # Request.get_json() could be first called with silent=True. delete_cached_json_for ( request ) return request . get_json ( silent = False , cache = False ) elif request . content_typ...
Extract payload from request .
119
6
8,749
def delete ( self , event ) : super ( CeleryReceiver , self ) . delete ( event ) AsyncResult ( event . id ) . revoke ( terminate = True )
Abort running task if it exists .
37
8
8,750
def validate_receiver ( self , key , value ) : if value not in current_webhooks . receivers : raise ReceiverDoesNotExist ( self . receiver_id ) return value
Validate receiver identifier .
40
5
8,751
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 .
65
5
8,752
def receiver ( self ) : try : return current_webhooks . receivers [ self . receiver_id ] except KeyError : raise ReceiverDoesNotExist ( self . receiver_id )
Return registered receiver .
40
4
8,753
def receiver ( self , value ) : assert isinstance ( value , Receiver ) self . receiver_id = value . receiver_id
Set receiver instance .
27
4
8,754
def process ( self ) : try : self . receiver ( self ) # TODO RESTException 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 .
65
4
8,755
def register_bootstrap_functions ( ) : # This can be called twice if '.pth' file bootstrapping works and # the 'autowrapt' wrapper script is still also used. We therefore # protect ourselves just in case it is called a second time as we # only want to force registration once. global _registered if _registered : return ...
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 .
169
36
8,756
def bootstrap ( ) : global _patched if _patched : return _patched = True # We want to do our real work as the very last thing in the 'site' # module when it is being imported so that the module search path is # initialised properly. What is the last thing executed depends on # whether the 'usercustomize' module support...
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 .
283
47
8,757
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
112
11
8,758
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
147
12
8,759
def get_arguments ( ) : # https://docs.python.org/3/library/argparse.html 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' , def...
This get us the cli arguments .
349
8
8,760
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 .
90
6
8,761
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 .
129
8
8,762
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...
Return a json payload and appropriate status code on expection .
136
12
8,763
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 ( ) # db.session.begin(subtransactions...
Handle POST request .
117
4
8,764
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 .
103
7
8,765
def get ( self , receiver_id = None , event_id = None ) : event = self . _get_event ( receiver_id , event_id ) return make_response ( event )
Handle GET request .
42
4
8,766
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 .
54
6
8,767
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
48
10
8,768
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
75
5
8,769
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
54
8
8,770
def _get_license_description ( license_code ) : req = requests . get ( "{base_url}/licenses/{license_code}" . format ( base_url = BASE_URL , license_code = license_code ) , headers = _HEADERS ) if req . status_code == requests . codes . ok : s = req . json ( ) [ "body" ] search_curly = re . search ( r'\{(.*)\}' , s ) s...
Gets the body for a license based on a license code
261
12
8,771
def get_license_summary ( license_code ) : try : abs_file = os . path . join ( _ROOT , "summary.json" ) with open ( abs_file , 'r' ) as f : summary_license = json . loads ( f . read ( ) ) [ license_code ] # prints summary print ( Fore . YELLOW + 'SUMMARY' ) print ( Style . RESET_ALL ) , print ( summary_license [ 'summa...
Gets the license summary and permitted forbidden and required behaviour
323
11
8,772
def main ( ) : arguments = docopt ( __doc__ , version = __version__ ) if arguments [ 'ls' ] or arguments [ 'list' ] : _get_licences ( ) elif arguments [ '--tldr' ] and arguments [ '<NAME>' ] : get_license_summary ( arguments [ '<NAME>' ] . lower ( ) ) elif arguments [ '--export' ] and arguments [ '<NAME>' ] : save_lice...
harvey helps you manage and add license from the command line
160
12
8,773
def get ( self , user_id ) : path = '/' . join ( [ 'person' , user_id ] ) return self . rachio . get ( path )
Retrieve the information for a person entity .
38
9
8,774
def copy_template ( self , name = None ) : ret = Table ( self . table_name ) ret . _indexes . update ( dict ( ( k , v . copy_template ( ) ) for k , v in self . _indexes . items ( ) ) ) ret ( name ) return ret
Create empty copy of the current table with copies of all index definitions .
65
14
8,775
def clone ( self , name = None ) : ret = self . copy_template ( ) . insert_many ( self . obs ) ( name ) return ret
Create full copy of the current table including table contents and index definitions .
33
14
8,776
def delete_index ( self , attr ) : if attr in self . _indexes : del self . _indexes [ attr ] self . _uniqueIndexes = [ ind for ind in self . _indexes . values ( ) if ind . is_unique ] return self
Deletes an index from the Table . Can be used to drop and rebuild an index or to convert a non - unique index to a unique index or vice versa .
61
33
8,777
def insert_many ( self , it ) : unique_indexes = self . _uniqueIndexes # [ind for ind in self._indexes.values() if ind.is_unique] NO_SUCH_ATTR = object ( ) new_objs = list ( it ) if unique_indexes : for ind in unique_indexes : ind_attr = ind . attr new_keys = dict ( ( getattr ( obj , ind_attr , NO_SUCH_ATTR ) , obj ) f...
Inserts a collection of objects into the table .
351
10
8,778
def remove_many ( self , it ) : # find indicies of objects in iterable to_be_deleted = list ( it ) del_indices = [ ] for i , ob in enumerate ( self . obs ) : try : tbd_index = to_be_deleted . index ( ob ) except ValueError : continue else : del_indices . append ( i ) to_be_deleted . pop ( tbd_index ) # quit early if we...
Removes a collection of objects from the table .
140
10
8,779
def _query_attr_sort_fn ( self , attr_val ) : attr , v = attr_val if attr in self . _indexes : idx = self . _indexes [ attr ] if v in idx : return len ( idx [ v ] ) else : return 0 else : return 1e9
Used to order where keys by most selective key first
74
10
8,780
def delete ( self , * * kwargs ) : if not kwargs : return 0 affected = self . where ( * * kwargs ) self . remove_many ( affected ) return len ( affected )
Deletes matching objects from the table based on given named parameters . If multiple named parameters are given then only objects that satisfy all of the query criteria will be removed .
45
33
8,781
def sort ( self , key , reverse = False ) : if isinstance ( key , ( basestring , list , tuple ) ) : if isinstance ( key , basestring ) : attrdefs = [ s . strip ( ) for s in key . split ( ',' ) ] attr_orders = [ ( a . split ( ) + [ 'asc' , ] ) [ : 2 ] for a in attrdefs ] else : # attr definitions were already resolved t...
Sort Table in place using given fields as sort key .
392
11
8,782
def select ( self , fields , * * exprs ) : fields = self . _parse_fields_string ( fields ) def _make_string_callable ( expr ) : if isinstance ( expr , basestring ) : return lambda r : expr % r else : return expr exprs = dict ( ( k , _make_string_callable ( v ) ) for k , v in exprs . items ( ) ) raw_tuples = [ ] for ob ...
Create a new table containing a subset of attributes with optionally newly - added fields computed from each rec in the original table .
266
24
8,783
def formatted_table ( self , * fields , * * exprs ) : # select_exprs = {} # for f in fields: # select_exprs[f] = lambda r : str(getattr,f,None) fields = set ( fields ) select_exprs = ODict ( ( f , lambda r , f = f : str ( getattr , f , None ) ) for f in fields ) for ename , expr in exprs . items ( ) : if isinstance ( e...
Create a new table with all string formatted attribute values typically in preparation for formatted output .
248
17
8,784
def join_on ( self , attr ) : if attr not in self . _indexes : raise ValueError ( "can only join on indexed attributes" ) return JoinTerm ( self , attr )
Creates a JoinTerm in preparation for joining with another table to indicate what attribute should be used in the join . Only indexed attributes may be used in a join .
44
33
8,785
def csv_import ( self , csv_source , encoding = 'utf-8' , transforms = None , row_class = DataObject , * * kwargs ) : reader_args = dict ( ( k , v ) for k , v in kwargs . items ( ) if k not in [ 'encoding' , 'csv_source' , 'transforms' , 'row_class' ] ) reader = lambda src : csv . DictReader ( src , * * reader_args ) r...
Imports the contents of a CSV - formatted file into this table .
137
14
8,786
def tsv_import ( self , xsv_source , encoding = "UTF-8" , transforms = None , row_class = DataObject , * * kwargs ) : return self . _xsv_import ( xsv_source , encoding , transforms = transforms , delimiter = "\t" , row_class = row_class , * * kwargs )
Imports the contents of a tab - separated data file into this table .
80
15
8,787
def csv_export ( self , csv_dest , fieldnames = None , encoding = "UTF-8" ) : close_on_exit = False if isinstance ( csv_dest , basestring ) : if PY_3 : csv_dest = open ( csv_dest , 'w' , newline = '' , encoding = encoding ) else : csv_dest = open ( csv_dest , 'wb' ) close_on_exit = True try : if fieldnames is None : fi...
Exports the contents of the table to a CSV - formatted file .
316
14
8,788
def json_import ( self , source , encoding = "UTF-8" , transforms = None , row_class = DataObject ) : class _JsonFileReader ( object ) : def __init__ ( self , src ) : self . source = src def __iter__ ( self ) : current = '' for line in self . source : if current : current += ' ' current += line try : yield json . loads...
Imports the contents of a JSON data file into this table .
128
13
8,789
def json_export ( self , dest , fieldnames = None , encoding = "UTF-8" ) : close_on_exit = False if isinstance ( dest , basestring ) : if PY_3 : dest = open ( dest , 'w' , encoding = encoding ) else : dest = open ( dest , 'w' ) close_on_exit = True try : if isinstance ( fieldnames , basestring ) : fieldnames = fieldnam...
Exports the contents of the table to a JSON - formatted file .
199
14
8,790
def add_field ( self , attrname , fn , default = None ) : # for rec in self: def _add_field_to_rec ( rec_ , fn_ = fn , default_ = default ) : try : val = fn_ ( rec_ ) except Exception : val = default_ if isinstance ( rec_ , DataObject ) : rec_ . __dict__ [ attrname ] = val else : setattr ( rec_ , attrname , val ) try :...
Computes a new attribute for each object in table or replaces an existing attribute in each record with a computed value
161
22
8,791
def groupby ( self , keyexpr , * * outexprs ) : if isinstance ( keyexpr , basestring ) : keyattrs = keyexpr . split ( ) keyfn = lambda o : tuple ( getattr ( o , k ) for k in keyattrs ) elif isinstance ( keyexpr , tuple ) : keyattrs = ( keyexpr [ 0 ] , ) keyfn = keyexpr [ 1 ] else : raise TypeError ( "keyexpr must be st...
simple prototype of group by with support for expressions in the group - by clause and outputs
259
17
8,792
def unique ( self , key = None ) : if isinstance ( key , basestring ) : key = lambda r , attr = key : getattr ( r , attr , None ) ret = self . copy_template ( ) seen = set ( ) for ob in self : if key is None : try : ob_dict = vars ( ob ) except TypeError : ob_dict = dict ( ( k , getattr ( ob , k ) ) for k in _object_at...
Create a new table of objects containing no duplicate values .
156
11
8,793
def as_html ( self , fields = '*' ) : fields = self . _parse_fields_string ( fields ) def td_value ( v ) : return '<td><div align="{}">{}</div></td>' . format ( ( 'left' , 'right' ) [ isinstance ( v , ( int , float ) ) ] , str ( v ) ) def row_to_tr ( r ) : return "<tr>" + "" . join ( td_value ( getattr ( r , fld ) ) fo...
Output the table as a rudimentary HTML table .
210
9
8,794
def dump ( self , out = sys . stdout , row_fn = repr , limit = - 1 , indent = 0 ) : NL = '\n' if indent : out . write ( " " * indent + self . pivot_key_str ( ) ) else : out . write ( "Pivot: %s" % ',' . join ( self . _pivot_attrs ) ) out . write ( NL ) if self . has_subtables ( ) : do_all ( sub . dump ( out , row_fn , ...
Dump out the contents of this table in a nested listing .
204
13
8,795
def dump_counts ( self , out = sys . stdout , count_fn = len , colwidth = 10 ) : if len ( self . _pivot_attrs ) == 1 : out . write ( "Pivot: %s\n" % ',' . join ( self . _pivot_attrs ) ) maxkeylen = max ( len ( str ( k ) ) for k in self . keys ( ) ) maxvallen = colwidth keytally = { } for k , sub in self . items ( ) : s...
Dump out the summary counts of entries in this pivot table as a tabular listing .
726
18
8,796
def as_table ( self , fn = None , col = None , col_label = None ) : if col_label is None : col_label = col if fn is None : fn = len if col_label is None : col_label = 'count' ret = Table ( ) # topattr = self._pivot_attrs[0] do_all ( ret . create_index ( attr ) for attr in self . _pivot_attrs ) if len ( self . _pivot_at...
Dump out the summary counts of this pivot table as a Table .
461
14
8,797
def _update_record ( record ) : # Standard fields dt = datetime . fromtimestamp ( record . created ) # Truncate microseconds to milliseconds record . springtime = str ( dt ) [ : - 3 ] record . levelname_spring = "WARN" if record . levelname == "WARNING" else record . levelname record . process_id = str ( os . getpid ( ...
Collates values needed by LOG_FORMAT
173
9
8,798
def _tracing_information ( ) : # We'll collate trace information if the B3 headers have been collected: values = b3 . values ( ) if values [ b3 . b3_trace_id ] : # Trace information would normally be sent to Zipkin if either of sampled or debug ("flags") is set to 1 # However we're not currently using Zipkin, so it's a...
Gets B3 distributed tracing information if available . This is returned as a list ready to be formatted into Spring Cloud Sleuth compatible format .
175
28
8,799
def _authenticate ( self ) : data = { 'username' : self . username , 'password' : self . password } url = '{base}/client/login' . format ( base = self . base_url ) response = self . _session . get ( url , params = data ) print ( response . text ) data = response . json ( ) if not data . get ( 'success' ) : raise Invali...
Authenticates to the api and sets up client information .
115
11