idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
232,400
def convolutional_layer_series ( initial_size , layer_sequence ) : size = initial_size for filter_size , padding , stride in layer_sequence : size = convolution_size_equation ( size , filter_size , padding , stride ) return size
Execute a series of convolutional layer transformations to the size number
232,401
def train ( self , mode = True ) : r super ( ) . train ( mode ) if mode : mu . apply_leaf ( self , mu . set_train_mode ) return self
r Sets the module in training mode .
232,402
def summary ( self , input_size = None , hashsummary = False ) : if input_size is None : print ( self ) print ( "-" * 120 ) number = sum ( p . numel ( ) for p in self . model . parameters ( ) ) print ( "Number of model parameters: {:,}" . format ( number ) ) print ( "-" * 120 ) else : summary ( self , input_size ) if h...
Print a model summary
232,403
def hashsummary ( self ) : children = list ( self . children ( ) ) result = [ ] for child in children : result . extend ( hashlib . sha256 ( x . detach ( ) . cpu ( ) . numpy ( ) . tobytes ( ) ) . hexdigest ( ) for x in child . parameters ( ) ) return result
Print a model summary - checksums of each layer parameters
232,404
def zero_state ( self , batch_size ) : return torch . zeros ( batch_size , self . state_dim , dtype = torch . float32 )
Initial state of the network
232,405
def loss ( self , x_data , y_true ) : y_pred = self ( x_data ) return y_pred , self . loss_value ( x_data , y_true , y_pred )
Forward propagate network and return a value of loss function
232,406
def metrics ( self ) : from vel . metrics . loss_metric import Loss from vel . metrics . accuracy import Accuracy return [ Loss ( ) , Accuracy ( ) ]
Set of metrics for this model
232,407
def one_hot_encoding ( input_tensor , num_labels ) : xview = input_tensor . view ( - 1 , 1 ) . to ( torch . long ) onehot = torch . zeros ( xview . size ( 0 ) , num_labels , device = input_tensor . device , dtype = torch . float ) onehot . scatter_ ( 1 , xview , 1 ) return onehot . view ( list ( input_tensor . shape ) ...
One - hot encode labels from input
232,408
def merge_first_two_dims ( tensor ) : shape = tensor . shape batch_size = shape [ 0 ] * shape [ 1 ] new_shape = tuple ( [ batch_size ] + list ( shape [ 2 : ] ) ) return tensor . view ( new_shape )
Reshape tensor to merge first two dimensions
232,409
def instantiate ( self , parallel_envs , seed = 0 , preset = 'default' ) -> VecEnv : envs = DummyVecEnv ( [ self . _creation_function ( i , seed , preset ) for i in range ( parallel_envs ) ] ) if self . frame_history is not None : envs = VecFrameStack ( envs , self . frame_history ) return envs
Create vectorized environments
232,410
def instantiate_single ( self , seed = 0 , preset = 'default' ) : env = self . env . instantiate ( seed = seed , serial_id = 0 , preset = preset ) if self . frame_history is not None : env = FrameStack ( env , self . frame_history ) return env
Create a new Env instance - single
232,411
def _creation_function ( self , idx , seed , preset ) : return lambda : self . env . instantiate ( seed = seed , serial_id = idx , preset = preset )
Helper function to create a proper closure around supplied values
232,412
def policy ( self , observations ) : input_data = self . input_block ( observations ) policy_base_output = self . policy_backbone ( input_data ) policy_params = self . action_head ( policy_base_output ) return policy_params
Calculate only action head for given state
232,413
def _init_cycle_dict ( self ) : dict_arr = np . zeros ( self . epochs , dtype = int ) length_arr = np . zeros ( self . epochs , dtype = int ) start_arr = np . zeros ( self . epochs , dtype = int ) c_len = self . cycle_len idx = 0 for i in range ( self . cycles ) : current_start = idx for j in range ( c_len ) : dict_arr...
Populate a cycle dict
232,414
def on_batch_begin ( self , batch_info : BatchInfo ) : cycle_length = self . cycle_lengths [ batch_info . local_epoch_number - 1 ] cycle_start = self . cycle_starts [ batch_info . local_epoch_number - 1 ] numerator = ( batch_info . local_epoch_number - cycle_start - 1 ) * batch_info . batches_per_epoch + batch_info . b...
Set proper learning rate
232,415
def set_lr ( self , lr ) : if isinstance ( lr , list ) : for group_lr , param_group in zip ( lr , self . optimizer . param_groups ) : param_group [ 'lr' ] = group_lr else : for param_group in self . optimizer . param_groups : param_group [ 'lr' ] = lr
Set a learning rate for the optimizer
232,416
def parameter_constructor ( cls , loader , node ) : value = loader . construct_scalar ( node ) if isinstance ( value , str ) : if '=' in value : ( varname , varvalue ) = Parser . parse_equality ( value ) return cls ( varname , varvalue ) else : return cls ( value ) else : return cls ( value )
Construct variable instance from yaml node
232,417
def register ( cls ) : if not cls . IS_LOADED : cls . IS_LOADED = True yaml . add_constructor ( '!param' , Parameter . parameter_constructor , Loader = yaml . SafeLoader ) yaml . add_constructor ( '!env' , EnvironmentVariable . parameter_constructor , Loader = yaml . SafeLoader )
Register variable handling in YAML
232,418
def parse_equality ( cls , equality_string ) : cls . register ( ) assert '=' in equality_string , "There must be an '=' sign in the equality" [ left_side , right_side ] = equality_string . split ( '=' , 1 ) left_side_value = yaml . safe_load ( left_side . strip ( ) ) right_side_value = yaml . safe_load ( right_side . s...
Parse some simple equality statements
232,419
def clean ( self , initial_epoch ) : self . db . metrics . delete_many ( { 'run_name' : self . model_config . run_name , 'epoch_idx' : { '$gt' : initial_epoch } } )
Remove entries from database that would get overwritten
232,420
def store_config ( self , configuration ) : run_name = self . model_config . run_name self . db . configs . delete_many ( { 'run_name' : self . model_config . run_name } ) configuration = configuration . copy ( ) configuration [ 'run_name' ] = run_name self . db . configs . insert_one ( configuration )
Store model parameters in the database
232,421
def get_frame ( self ) : metric_items = list ( self . db . metrics . find ( { 'run_name' : self . model_config . run_name } ) . sort ( 'epoch_idx' ) ) if len ( metric_items ) == 0 : return pd . DataFrame ( columns = [ 'run_name' ] ) else : return pd . DataFrame ( metric_items ) . drop ( [ '_id' , 'model_name' ] , axis ...
Get a dataframe of metrics from this storage
232,422
def _get_transitions ( self , probs , indexes , tree_idxs , batch_info , forward_steps = 1 , discount_factor = 1.0 ) : if forward_steps > 1 : transition_arrays = self . backend . get_transitions_forward_steps ( indexes , forward_steps , discount_factor ) else : transition_arrays = self . backend . get_transitions ( ind...
Return batch of frames for given indexes
232,423
def rollout ( self , batch_info : BatchInfo , model : Model , number_of_steps : int ) -> Rollout : raise NotImplementedError
Roll - out the environment and return it
232,424
def train_epoch ( self , epoch_info : EpochInfo , interactive = True ) : epoch_info . on_epoch_begin ( ) if interactive : iterator = tqdm . trange ( epoch_info . batches_per_epoch , file = sys . stdout , desc = "Training" , unit = "batch" ) else : iterator = range ( epoch_info . batches_per_epoch ) for batch_idx in ite...
Train model on an epoch of a fixed number of batch updates
232,425
def train_batch ( self , batch_info : BatchInfo ) : batch_info [ 'sub_batch_data' ] = [ ] self . on_policy_train_batch ( batch_info ) if self . settings . experience_replay > 0 and self . env_roller . is_ready_for_sampling ( ) : if self . settings . stochastic_experience_replay : experience_replay_count = np . random ....
Single most atomic step of learning this reinforcer can perform
232,426
def on_policy_train_batch ( self , batch_info : BatchInfo ) : self . model . train ( ) rollout = self . env_roller . rollout ( batch_info , self . model , self . settings . number_of_steps ) . to_device ( self . device ) batch_result = self . algo . optimizer_step ( batch_info = batch_info , device = self . device , mo...
Perform an on - policy training step of evaluating an env and a single backpropagation step
232,427
def off_policy_train_batch ( self , batch_info : BatchInfo ) : self . model . train ( ) rollout = self . env_roller . sample ( batch_info , self . model , self . settings . number_of_steps ) . to_device ( self . device ) batch_result = self . algo . optimizer_step ( batch_info = batch_info , device = self . device , mo...
Perform an off - policy training step of sampling the replay buffer and gradient descent
232,428
def should_store_best_checkpoint ( self , epoch_idx , metrics ) -> bool : if not self . store_best : return False metric = metrics [ self . metric ] if better ( self . _current_best_metric_value , metric , self . metric_mode ) : self . _current_best_metric_value = metric return True return False
Should we store current checkpoint as the best
232,429
def create ( model_config , batch_size , vectors = None ) : path = model_config . data_dir ( 'imdb' ) text_field = data . Field ( lower = True , tokenize = 'spacy' , batch_first = True ) label_field = data . LabelField ( is_target = True ) train_source , test_source = IMDBCached . splits ( root = path , text_field = te...
Create an IMDB dataset
232,430
def run ( self ) : dataset = self . source . train_dataset ( ) num_samples = len ( dataset ) fig , ax = plt . subplots ( self . cases , self . samples + 1 ) selected_sample = np . sort ( np . random . choice ( num_samples , self . cases , replace = False ) ) for i in range ( self . cases ) : raw_image , _ = dataset . g...
Run the visualization
232,431
def env_maker ( environment_id , seed , serial_id , monitor = False , allow_early_resets = False ) : env = gym . make ( environment_id ) env . seed ( seed + serial_id ) if monitor : logdir = logger . get_dir ( ) and os . path . join ( logger . get_dir ( ) , str ( serial_id ) ) else : logdir = None env = Monitor ( env ,...
Create a classic control environment with basic set of wrappers
232,432
def freeze ( self , number = None ) : if number is None : number = self . head_layers for idx , child in enumerate ( self . model . children ( ) ) : if idx < number : mu . freeze_layer ( child )
Freeze given number of layers in the model
232,433
def unfreeze ( self ) : for idx , child in enumerate ( self . model . children ( ) ) : mu . unfreeze_layer ( child )
Unfreeze model layers
232,434
def update_average_model ( self , model ) : for model_param , average_param in zip ( model . parameters ( ) , self . average_model . parameters ( ) ) : average_param . data . mul_ ( self . average_model_alpha ) . add_ ( model_param . data * ( 1 - self . average_model_alpha ) )
Update weights of the average model with new model observation
232,435
def retrace ( self , rewards , dones , q_values , state_values , rho , final_values ) : rho_bar = torch . min ( torch . ones_like ( rho ) * self . retrace_rho_cap , rho ) q_retraced_buffer = torch . zeros_like ( rewards ) next_value = final_values for i in reversed ( range ( rewards . size ( 0 ) ) ) : q_retraced = rewa...
Calculate Q retraced targets
232,436
def logprob ( self , action_sample , pd_params ) : means = pd_params [ : , : , 0 ] log_std = pd_params [ : , : , 1 ] std = torch . exp ( log_std ) z_score = ( action_sample - means ) / std return - ( 0.5 * ( ( z_score ** 2 + self . LOG2PI ) . sum ( dim = - 1 ) ) + log_std . sum ( dim = - 1 ) )
Log - likelihood
232,437
def logprob ( self , actions , action_logits ) : neg_log_prob = F . nll_loss ( action_logits , actions , reduction = 'none' ) return - neg_log_prob
Logarithm of probability of given sample
232,438
def _value_function ( self , x_input , y_true , y_pred ) : if len ( y_true . shape ) == 1 : return y_pred . argmax ( 1 ) . eq ( y_true ) . double ( ) . mean ( ) . item ( ) else : raise NotImplementedError
Return classification accuracy of input
232,439
def on_epoch_end ( self , epoch_info ) : metrics_df = pd . DataFrame ( [ epoch_info . result ] ) . set_index ( 'epoch_idx' ) visdom_append_metrics ( self . vis , metrics_df , first_epoch = epoch_info . global_epoch_idx == 1 )
Update data in visdom on push
232,440
def on_batch_end ( self , batch_info ) : if self . settings . stream_lr : iteration_idx = ( float ( batch_info . epoch_number ) + float ( batch_info . batch_number ) / batch_info . batches_per_epoch ) lr = batch_info . optimizer . param_groups [ - 1 ] [ 'lr' ] metrics_df = pd . DataFrame ( [ lr ] , index = [ iteration_...
Stream LR to visdom
232,441
def main ( ) : parser = argparse . ArgumentParser ( description = 'Paperboy deep learning launcher' ) parser . add_argument ( 'config' , metavar = 'FILENAME' , help = 'Configuration file for the run' ) parser . add_argument ( 'command' , metavar = 'COMMAND' , help = 'A command to run' ) parser . add_argument ( 'varargs...
Paperboy entry point - parse the arguments and run a command
232,442
def set_seed ( seed : int ) : random . seed ( seed ) np . random . seed ( seed ) torch . random . manual_seed ( seed )
Set random seed for python numpy and pytorch RNGs
232,443
def better ( old_value , new_value , mode ) : if ( old_value is None or np . isnan ( old_value ) ) and ( new_value is not None and not np . isnan ( new_value ) ) : return True if mode == 'min' : return new_value < old_value elif mode == 'max' : return new_value > old_value else : raise RuntimeError ( f"Mode '{mode}' va...
Check if new value is better than the old value
232,444
def reset_weights ( self ) : init . uniform_ ( self . linear . weight , - 3e-3 , 3e-3 ) init . zeros_ ( self . linear . bias )
Initialize weights to sane defaults
232,445
def discount_bootstrap ( rewards_buffer , dones_buffer , final_values , discount_factor , number_of_steps ) : true_value_buffer = torch . zeros_like ( rewards_buffer ) current_value = final_values for i in reversed ( range ( number_of_steps ) ) : current_value = rewards_buffer [ i ] + discount_factor * current_value * ...
Calculate state values bootstrapping off the following state values
232,446
def find_project_directory ( start_path ) -> str : start_path = os . path . realpath ( start_path ) possible_name = os . path . join ( start_path , ModelConfig . PROJECT_FILE_NAME ) if os . path . exists ( possible_name ) : return start_path else : up_path = os . path . realpath ( os . path . join ( start_path , '..' )...
Locate top - level project directory
232,447
def from_file ( cls , filename : str , run_number : int , continue_training : bool = False , seed : int = None , device : str = 'cuda' , params = None ) : with open ( filename , 'r' ) as fp : model_config_contents = Parser . parse ( fp ) project_config_path = ModelConfig . find_project_directory ( os . path . dirname (...
Create model config from file
232,448
def from_memory ( cls , model_data : dict , run_number : int , project_dir : str , continue_training = False , seed : int = None , device : str = 'cuda' , params = None ) : return ModelConfig ( filename = "[memory]" , configuration = model_data , run_number = run_number , project_dir = project_dir , continue_training =...
Create model config from supplied data
232,449
def run_command ( self , command_name , varargs ) : command_descriptor = self . get_command ( command_name ) return command_descriptor . run ( * varargs )
Instantiate model class
232,450
def project_data_dir ( self , * args ) -> str : return os . path . normpath ( os . path . join ( self . project_dir , 'data' , * args ) )
Directory where to store data
232,451
def output_dir ( self , * args ) -> str : return os . path . join ( self . project_dir , 'output' , * args )
Directory where to store output
232,452
def project_top_dir ( self , * args ) -> str : return os . path . join ( self . project_dir , * args )
Project top - level directory
232,453
def provide_with_default ( self , name , default = None ) : return self . provider . instantiate_by_name_with_default ( name , default_value = default )
Return a dependency - injected instance
232,454
def benchmark_method ( f ) : "decorator to turn f into a factory of benchmarks" @ wraps ( f ) def inner ( name , * args , ** kwargs ) : return Benchmark ( name , f , args , kwargs ) return inner
decorator to turn f into a factory of benchmarks
232,455
def bench ( participants = participants , benchmarks = benchmarks , bench_time = BENCH_TIME ) : mcs = [ p . factory ( ) for p in participants ] means = [ [ ] for p in participants ] stddevs = [ [ ] for p in participants ] last_fn = None for benchmark_name , fn , args , kwargs in benchmarks : logger . info ( '' ) logger...
Do you even lift?
232,456
def strip_datetime ( value ) : if isinstance ( value , basestring ) : try : return parse_datetime ( value ) except ValueError : return elif isinstance ( value , integer_types ) : try : return datetime . datetime . utcfromtimestamp ( value / 1e3 ) except ( ValueError , OverflowError , OSError ) : return
Converts value to datetime if string or int .
232,457
def set_session_token ( self , session_token ) : self . session_token = session_token self . _login_time = datetime . datetime . now ( )
Sets session token and new login time .
232,458
def get_password ( self ) : if self . password is None : if os . environ . get ( self . username + 'password' ) : self . password = os . environ . get ( self . username + 'password' ) else : raise PasswordError ( self . username )
If password is not provided will look in environment variables for username + password .
232,459
def get_app_key ( self ) : if self . app_key is None : if os . environ . get ( self . username ) : self . app_key = os . environ . get ( self . username ) else : raise AppKeyError ( self . username )
If app_key is not provided will look in environment variables for username .
232,460
def session_expired ( self ) : if not self . _login_time or ( datetime . datetime . now ( ) - self . _login_time ) . total_seconds ( ) > 12000 : return True
Returns True if login_time not set or seconds since login time is greater than 200 mins .
232,461
def check_status_code ( response , codes = None ) : codes = codes or [ 200 ] if response . status_code not in codes : raise StatusCodeError ( response . status_code )
Checks response . status_code is in codes .
232,462
def list_runner_book ( self , market_id , selection_id , handicap = None , price_projection = None , order_projection = None , match_projection = None , include_overall_position = None , partition_matched_by_strategy_ref = None , customer_strategy_refs = None , currency_code = None , matched_since = None , bet_ids = No...
Returns a list of dynamic data about a market and a specified runner . Dynamic data includes prices the status of the market the status of selections the traded volume and the status of any orders you have placed in the market
232,463
def list_current_orders ( self , bet_ids = None , market_ids = None , order_projection = None , customer_order_refs = None , customer_strategy_refs = None , date_range = time_range ( ) , order_by = None , sort_dir = None , from_record = None , record_count = None , session = None , lightweight = None ) : params = clean...
Returns a list of your current orders .
232,464
def list_cleared_orders ( self , bet_status = 'SETTLED' , event_type_ids = None , event_ids = None , market_ids = None , runner_ids = None , bet_ids = None , customer_order_refs = None , customer_strategy_refs = None , side = None , settled_date_range = time_range ( ) , group_by = None , include_item_description = None...
Returns a list of settled bets based on the bet status ordered by settled date .
232,465
def list_market_profit_and_loss ( self , market_ids , include_settled_bets = None , include_bsp_bets = None , net_of_commission = None , session = None , lightweight = None ) : params = clean_locals ( locals ( ) ) method = '%s%s' % ( self . URI , 'listMarketProfitAndLoss' ) ( response , elapsed_time ) = self . request ...
Retrieve profit and loss for a given list of OPEN markets .
232,466
def place_orders ( self , market_id , instructions , customer_ref = None , market_version = None , customer_strategy_ref = None , async_ = None , session = None , lightweight = None ) : params = clean_locals ( locals ( ) ) method = '%s%s' % ( self . URI , 'placeOrders' ) ( response , elapsed_time ) = self . request ( m...
Place new orders into market .
232,467
def serialise ( self ) : return { 'marketId' : self . market_id , 'totalAvailable' : None , 'isMarketDataDelayed' : None , 'lastMatchTime' : None , 'betDelay' : self . market_definition . get ( 'betDelay' ) , 'version' : self . market_definition . get ( 'version' ) , 'complete' : self . market_definition . get ( 'compl...
Creates standard market book json response will error if EX_MARKET_DEF not incl .
232,468
def list_race_details ( self , meeting_ids = None , race_ids = None , session = None , lightweight = None ) : params = clean_locals ( locals ( ) ) method = '%s%s' % ( self . URI , 'listRaceDetails' ) ( response , elapsed_time ) = self . request ( method , params , session ) return self . process_response ( response , r...
Search for races to get their details .
232,469
def list_available_events ( self , event_ids = None , event_type_ids = None , event_status = None , session = None , lightweight = None ) : params = clean_locals ( locals ( ) ) method = '%s%s' % ( self . URI , 'listAvailableEvents' ) ( response , elapsed_time ) = self . request ( method , params , session ) return self...
Search for events that have live score data available .
232,470
def list_scores ( self , update_keys , session = None , lightweight = None ) : params = clean_locals ( locals ( ) ) method = '%s%s' % ( self . URI , 'listScores' ) ( response , elapsed_time ) = self . request ( method , params , session ) return self . process_response ( response , resources . Score , elapsed_time , li...
Returns a list of current scores for the given events .
232,471
def list_incidents ( self , update_keys , session = None , lightweight = None ) : params = clean_locals ( locals ( ) ) method = '%s%s' % ( self . URI , 'listIncidents' ) ( response , elapsed_time ) = self . request ( method , params , session ) return self . process_response ( response , resources . Incidents , elapsed...
Returns a list of incidents for the given events .
232,472
def get_event_timeline ( self , event_id , session = None , lightweight = None ) : url = '%s%s' % ( self . url , 'eventTimeline' ) params = { 'eventId' : event_id , 'alt' : 'json' , 'regionCode' : 'UK' , 'locale' : 'en_GB' } ( response , elapsed_time ) = self . request ( params = params , session = session , url = url ...
Returns event timeline for event id provided .
232,473
def get_event_timelines ( self , event_ids , session = None , lightweight = None ) : url = '%s%s' % ( self . url , 'eventTimelines' ) params = { 'eventIds' : ',' . join ( str ( x ) for x in event_ids ) , 'alt' : 'json' , 'regionCode' : 'UK' , 'locale' : 'en_GB' } ( response , elapsed_time ) = self . request ( params = ...
Returns a list of event timelines based on event id s supplied .
232,474
def get_scores ( self , event_ids , session = None , lightweight = None ) : url = '%s%s' % ( self . url , 'scores' ) params = { 'eventIds' : ',' . join ( str ( x ) for x in event_ids ) , 'alt' : 'json' , 'regionCode' : 'UK' , 'locale' : 'en_GB' } ( response , elapsed_time ) = self . request ( params = params , session ...
Returns a list of scores based on event id s supplied .
232,475
def create_stream ( self , unique_id = 0 , listener = None , timeout = 11 , buffer_size = 1024 , description = 'BetfairSocket' , host = None ) : listener = listener if listener else BaseListener ( ) return BetfairStream ( unique_id , listener , app_key = self . client . app_key , session_token = self . client . session...
Creates BetfairStream .
232,476
def get_my_data ( self , session = None ) : params = clean_locals ( locals ( ) ) method = 'GetMyData' ( response , elapsed_time ) = self . request ( method , params , session ) return response
Returns a list of data descriptions for data which has been purchased by the signed in user .
232,477
def get_data_size ( self , sport , plan , from_day , from_month , from_year , to_day , to_month , to_year , event_id = None , event_name = None , market_types_collection = None , countries_collection = None , file_type_collection = None , session = None ) : params = clean_locals ( locals ( ) ) method = 'GetAdvBasketDat...
Returns a dictionary of file count and combines size files .
232,478
def login ( self , session = None ) : session = session or self . client . session try : response = session . get ( self . login_url ) except ConnectionError : raise APIError ( None , self . login_url , None , 'ConnectionError' ) except Exception as e : raise APIError ( None , self . login_url , None , e ) app_key = re...
Parses app key from betfair exchange site .
232,479
def get_race_card ( self , market_ids , data_entries = None , session = None , lightweight = None ) : if not self . app_key : raise RaceCardError ( "You need to login before requesting a race_card\n" "APIClient.race_card.login()" ) params = self . create_race_card_req ( market_ids , data_entries ) ( response , elapsed_...
Returns a list of race cards based on market ids provided .
232,480
def on_data ( self , raw_data ) : try : data = json . loads ( raw_data ) except ValueError : logger . error ( 'value error: %s' % raw_data ) return unique_id = data . get ( 'id' ) if self . _error_handler ( data , unique_id ) : return False operation = data [ 'op' ] if operation == 'connection' : self . _on_connection ...
Called when raw data is received from connection . Override this method if you wish to manually handle the stream data
232,481
def _on_connection ( self , data , unique_id ) : if unique_id is None : unique_id = self . stream_unique_id self . connection_id = data . get ( 'connectionId' ) logger . info ( '[Connect: %s]: connection_id: %s' % ( unique_id , self . connection_id ) )
Called on collection operation
232,482
def _on_status ( data , unique_id ) : status_code = data . get ( 'statusCode' ) logger . info ( '[Subscription: %s]: %s' % ( unique_id , status_code ) )
Called on status operation
232,483
def _error_handler ( data , unique_id ) : if data . get ( 'statusCode' ) == 'FAILURE' : logger . error ( '[Subscription: %s] %s: %s' % ( unique_id , data . get ( 'errorCode' ) , data . get ( 'errorMessage' ) ) ) if data . get ( 'connectionClosed' ) : return True if data . get ( 'status' ) : logger . warning ( '[Subscri...
Called when data first received
232,484
def stop ( self ) : self . _running = False if self . _socket is None : return try : self . _socket . shutdown ( socket . SHUT_RDWR ) self . _socket . close ( ) except socket . error : pass self . _socket = None
Stops read loop and closes socket if it has been created .
232,485
def authenticate ( self ) : unique_id = self . new_unique_id ( ) message = { 'op' : 'authentication' , 'id' : unique_id , 'appKey' : self . app_key , 'session' : self . session_token , } self . _send ( message ) return unique_id
Authentication request .
232,486
def heartbeat ( self ) : unique_id = self . new_unique_id ( ) message = { 'op' : 'heartbeat' , 'id' : unique_id , } self . _send ( message ) return unique_id
Heartbeat request to keep session alive .
232,487
def subscribe_to_markets ( self , market_filter , market_data_filter , initial_clk = None , clk = None , conflate_ms = None , heartbeat_ms = None , segmentation_enabled = True ) : unique_id = self . new_unique_id ( ) message = { 'op' : 'marketSubscription' , 'id' : unique_id , 'marketFilter' : market_filter , 'marketDa...
Market subscription request .
232,488
def subscribe_to_orders ( self , order_filter = None , initial_clk = None , clk = None , conflate_ms = None , heartbeat_ms = None , segmentation_enabled = True ) : unique_id = self . new_unique_id ( ) message = { 'op' : 'orderSubscription' , 'id' : unique_id , 'orderFilter' : order_filter , 'initialClk' : initial_clk ,...
Order subscription request .
232,489
def _create_socket ( self ) : s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) s = ssl . wrap_socket ( s ) s . connect ( ( self . host , self . __port ) ) s . settimeout ( self . timeout ) return s
Creates ssl socket connects to stream api and sets timeout .
232,490
def _read_loop ( self ) : while self . _running : received_data_raw = self . _receive_all ( ) if self . _running : self . receive_count += 1 self . datetime_last_received = datetime . datetime . utcnow ( ) received_data_split = received_data_raw . split ( self . __CRLF ) for received_data in received_data_split : if re...
Read loop splits by CRLF and pushes received data to _data .
232,491
def _receive_all ( self ) : ( data , part ) = ( '' , '' ) if is_py3 : crlf_bytes = bytes ( self . __CRLF , encoding = self . __encoding ) else : crlf_bytes = self . __CRLF while self . _running and part [ - 2 : ] != crlf_bytes : try : part = self . _socket . recv ( self . buffer_size ) except ( socket . timeout , socke...
Whilst socket is running receives data from socket till CRLF is detected .
232,492
def _data ( self , received_data ) : if self . listener . on_data ( received_data ) is False : self . stop ( ) raise ListenerError ( self . listener . connection_id , received_data )
Sends data to listener if False is returned ; socket is closed .
232,493
def _send ( self , message ) : if not self . _running : self . _connect ( ) self . authenticate ( ) message_dumped = json . dumps ( message ) + self . __CRLF try : self . _socket . send ( message_dumped . encode ( ) ) except ( socket . timeout , socket . error ) as e : self . stop ( ) raise SocketError ( '[Connect: %s]...
If not running connects socket and authenticates . Adds CRLF and sends message to Betfair .
232,494
def fit_transform ( self , X , y = None , ** fit_params ) : Xt , yt , fit_params = self . _fit ( X , y , ** fit_params ) if isinstance ( self . _final_estimator , XyTransformerMixin ) : Xt , yt , _ = self . _final_estimator . fit_transform ( Xt , yt ) else : if hasattr ( self . _final_estimator , 'fit_transform' ) : Xt...
Fit the model and transform with the final estimator Fits all the transforms one after the other and transforms the data then uses fit_transform on transformed data with the final estimator .
232,495
def predict ( self , X ) : Xt , _ , _ = self . _transform ( X ) return self . _final_estimator . predict ( Xt )
Apply transforms to the data and predict with the final estimator
232,496
def transform_predict ( self , X , y ) : Xt , yt , _ = self . _transform ( X , y ) yp = self . _final_estimator . predict ( Xt ) return yt , yp
Apply transforms to the data and predict with the final estimator . Unlike predict this also returns the transformed target
232,497
def score ( self , X , y = None , sample_weight = None ) : Xt , yt , swt = self . _transform ( X , y , sample_weight ) self . N_test = len ( yt ) score_params = { } if swt is not None : score_params [ 'sample_weight' ] = swt if self . scorer is None : return self . _final_estimator . score ( Xt , yt , ** score_params )...
Apply transforms and score with the final estimator
232,498
def predict_proba ( self , X ) : Xt , _ , _ = self . _transform ( X ) return self . _final_estimator . predict_proba ( Xt )
Apply transforms and predict_proba of the final estimator
232,499
def decision_function ( self , X ) : Xt , _ , _ = self . _transform ( X ) return self . _final_estimator . decision_function ( Xt )
Apply transforms and decision_function of the final estimator