idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
249,700 | def get_redis_info ( ) : from kombu . utils . url import _parse_url as parse_redis_url from redis import ( StrictRedis , ConnectionError as RedisConnectionError , ResponseError as RedisResponseError , ) for conf_name in ( 'REDIS_URL' , 'BROKER_URL' , 'CELERY_BROKER_URL' ) : if hasattr ( settings , conf_name ) : url = g... | Check Redis connection . |
249,701 | def get_elasticsearch_info ( ) : from elasticsearch import ( Elasticsearch , ConnectionError as ESConnectionError ) if hasattr ( settings , 'ELASTICSEARCH_URL' ) : url = settings . ELASTICSEARCH_URL else : return { "status" : NO_CONFIG } start = datetime . now ( ) try : search = Elasticsearch ( url , request_timeout = ... | Check Elasticsearch connection . |
249,702 | def get_celery_info ( ) : import celery if not getattr ( settings , 'USE_CELERY' , False ) : log . error ( "No celery config found. Set USE_CELERY in settings to enable." ) return { "status" : NO_CONFIG } start = datetime . now ( ) try : app = celery . Celery ( 'tasks' ) app . config_from_object ( 'django.conf:settings... | Check celery availability |
249,703 | def get_certificate_info ( ) : if hasattr ( settings , 'MIT_WS_CERTIFICATE' ) and settings . MIT_WS_CERTIFICATE : mit_ws_certificate = settings . MIT_WS_CERTIFICATE else : return { "status" : NO_CONFIG } app_cert = OpenSSL . crypto . load_certificate ( OpenSSL . crypto . FILETYPE_PEM , ( mit_ws_certificate if not isins... | checks app certificate expiry status |
249,704 | def _start ( self ) : if self . whoami is None : me = self . get_me ( ) if me . get ( 'ok' , False ) : self . whoami = me [ 'result' ] else : raise ValueError ( 'Bot Cannot request information, check ' 'api_key' ) | Requests bot information based on current api_key and sets self . whoami to dictionary with username first_name and id of the configured bot . |
249,705 | def poll ( self , offset = None , poll_timeout = 600 , cooldown = 60 , debug = False ) : if self . config [ 'api_key' ] is None : raise ValueError ( 'config api_key is undefined' ) if offset or self . config . get ( 'offset' , None ) : self . offset = offset or self . config . get ( 'offset' , None ) self . _start ( ) ... | These should also be in the config section but some here for overrides |
249,706 | def get_attr ( obj , attr , default = None ) : if '.' not in attr : return getattr ( obj , attr , default ) else : L = attr . split ( '.' ) return get_attr ( getattr ( obj , L [ 0 ] , default ) , '.' . join ( L [ 1 : ] ) , default ) | Recursive get object s attribute . May use dot notation . |
249,707 | def asset ( path ) : commit = bitcaster . get_full_version ( ) return mark_safe ( '{0}?{1}' . format ( _static ( path ) , commit ) ) | Join the given path with the STATIC_URL setting . |
249,708 | def get_client_ip ( request ) : try : return request . META [ 'HTTP_X_FORWARDED_FOR' ] . split ( ',' ) [ 0 ] . strip ( ) except ( KeyError , IndexError ) : return request . META . get ( 'REMOTE_ADDR' ) | Naively yank the first IP address in an X - Forwarded - For header and assume this is correct . |
249,709 | def _pack_image ( filename , max_size , form_field = 'image' , f = None ) : if f is None : try : if os . path . getsize ( filename ) > ( max_size * 1024 ) : raise TweepError ( 'File is too big, must be less than %skb.' % max_size ) except os . error as e : raise TweepError ( 'Unable to access file: %s' % e . strerror )... | Pack image from file into multipart - formdata post body |
249,710 | def channel_submit_row ( context ) : change = context [ 'change' ] is_popup = context [ 'is_popup' ] save_as = context [ 'save_as' ] show_save = context . get ( 'show_save' , True ) show_save_and_continue = context . get ( 'show_save_and_continue' , True ) can_delete = context [ 'has_delete_permission' ] can_add = cont... | Display the row of buttons for delete and save . |
249,711 | def get_setting ( self , name ) : notfound = object ( ) "get configuration from 'constance.config' first " value = getattr ( config , name , notfound ) if name . endswith ( '_WHITELISTED_DOMAINS' ) : if value : return value . split ( ',' ) else : return [ ] if value is notfound : value = getattr ( settings , name ) if ... | get configuration from constance . config first |
249,712 | def debug ( self , request , message , extra_tags = '' , fail_silently = False ) : add ( self . target_name , request , constants . DEBUG , message , extra_tags = extra_tags , fail_silently = fail_silently ) | Add a message with the DEBUG level . |
249,713 | def info ( self , request , message , extra_tags = '' , fail_silently = False ) : add ( self . target_name , request , constants . INFO , message , extra_tags = extra_tags , fail_silently = fail_silently ) | Add a message with the INFO level . |
249,714 | def success ( self , request , message , extra_tags = '' , fail_silently = False ) : add ( self . target_name , request , constants . SUCCESS , message , extra_tags = extra_tags , fail_silently = fail_silently ) | Add a message with the SUCCESS level . |
249,715 | def warning ( self , request , message , extra_tags = '' , fail_silently = False ) : add ( self . target_name , request , constants . WARNING , message , extra_tags = extra_tags , fail_silently = fail_silently ) | Add a message with the WARNING level . |
249,716 | def error ( self , request , message , extra_tags = '' , fail_silently = False ) : add ( self . target_name , request , constants . ERROR , message , extra_tags = extra_tags , fail_silently = fail_silently ) | Add a message with the ERROR level . |
249,717 | def signup ( request , signup_form = SignupForm , template_name = 'userena/signup_form.html' , success_url = None , extra_context = None ) : if userena_settings . USERENA_DISABLE_SIGNUP : raise PermissionDenied if userena_settings . USERENA_WITHOUT_USERNAMES and ( signup_form == SignupForm ) : signup_form = SignupFormO... | Signup of an account . |
249,718 | def extend ( self , other ) : overlap = [ key for key in other . defaults if key in self . defaults ] if overlap : raise ValueError ( "Duplicate hyperparameter(s): %s" % " " . join ( overlap ) ) new = dict ( self . defaults ) new . update ( other . defaults ) return HyperparameterDefaults ( ** new ) | Return a new HyperparameterDefaults instance containing the hyperparameters from the current instance combined with those from other . |
249,719 | def with_defaults ( self , obj ) : self . check_valid_keys ( obj ) obj = dict ( obj ) for ( key , value ) in self . defaults . items ( ) : if key not in obj : obj [ key ] = value return obj | Given a dict of hyperparameter settings return a dict containing those settings augmented by the defaults for any keys missing from the dict . |
249,720 | def subselect ( self , obj ) : return dict ( ( key , value ) for ( key , value ) in obj . items ( ) if key in self . defaults ) | Filter a dict of hyperparameter settings to only those keys defined in this HyperparameterDefaults . |
249,721 | def check_valid_keys ( self , obj ) : invalid_keys = [ x for x in obj if x not in self . defaults ] if invalid_keys : raise ValueError ( "No such model parameters: %s. Valid parameters are: %s" % ( " " . join ( invalid_keys ) , " " . join ( self . defaults ) ) ) | Given a dict of hyperparameter settings throw an exception if any keys are not defined in this HyperparameterDefaults instance . |
249,722 | def models_grid ( self , ** kwargs ) : self . check_valid_keys ( kwargs ) for ( key , value ) in kwargs . items ( ) : if not isinstance ( value , list ) : raise ValueError ( "All parameters must be lists, but %s is %s" % ( key , str ( type ( value ) ) ) ) parameters = dict ( ( key , [ value ] ) for ( key , value ) in s... | Make a grid of models by taking the cartesian product of all specified model parameter lists . |
249,723 | def fixed_length_vector_encoded_sequences ( self , vector_encoding_name ) : cache_key = ( "fixed_length_vector_encoding" , vector_encoding_name ) if cache_key not in self . encoding_cache : index_encoded_matrix = amino_acid . index_encoding ( self . fixed_length_sequences . values , amino_acid . AMINO_ACID_INDEX ) vect... | Encode alleles . |
249,724 | def index_encoding ( sequences , letter_to_index_dict ) : df = pandas . DataFrame ( iter ( s ) for s in sequences ) result = df . replace ( letter_to_index_dict ) return result . values | Encode a sequence of same - length strings to a matrix of integers of the same shape . The map from characters to integers is given by letter_to_index_dict . |
249,725 | def apply_hyperparameter_renames ( cls , hyperparameters ) : for ( from_name , to_name ) in cls . hyperparameter_renames . items ( ) : if from_name in hyperparameters : value = hyperparameters . pop ( from_name ) if to_name : hyperparameters [ to_name ] = value return hyperparameters | Handle hyperparameter renames . |
249,726 | def borrow_cached_network ( klass , network_json , network_weights ) : assert network_weights is not None key = klass . keras_network_cache_key ( network_json ) if key not in klass . KERAS_MODELS_CACHE : import keras . models network = keras . models . model_from_json ( network_json ) existing_weights = None else : ( n... | Return a keras Model with the specified architecture and weights . As an optimization when possible this will reuse architectures from a process - wide cache . |
249,727 | def network ( self , borrow = False ) : if self . _network is None and self . network_json is not None : self . load_weights ( ) if borrow : return self . borrow_cached_network ( self . network_json , self . network_weights ) else : import keras . models self . _network = keras . models . model_from_json ( self . netwo... | Return the keras model associated with this predictor . |
249,728 | def load_weights ( self ) : if self . network_weights_loader : self . network_weights = self . network_weights_loader ( ) self . network_weights_loader = None | Load weights by evaluating self . network_weights_loader if needed . |
249,729 | def predict ( self , peptides , allele_encoding = None , batch_size = 4096 ) : assert self . prediction_cache is not None use_cache = ( allele_encoding is None and isinstance ( peptides , EncodableSequences ) ) if use_cache and peptides in self . prediction_cache : return self . prediction_cache [ peptides ] . copy ( )... | Predict affinities . |
249,730 | def make_scores ( ic50_y , ic50_y_pred , sample_weight = None , threshold_nm = 500 , max_ic50 = 50000 ) : y_pred = from_ic50 ( ic50_y_pred , max_ic50 ) try : auc = sklearn . metrics . roc_auc_score ( ic50_y <= threshold_nm , y_pred , sample_weight = sample_weight ) except ValueError as e : logging . warning ( e ) auc =... | Calculate AUC F1 and Kendall Tau scores . |
249,731 | def variable_length_to_fixed_length_vector_encoding ( self , vector_encoding_name , left_edge = 4 , right_edge = 4 , max_length = 15 ) : cache_key = ( "fixed_length_vector_encoding" , vector_encoding_name , left_edge , right_edge , max_length ) if cache_key not in self . encoding_cache : fixed_length_sequences = ( self... | Encode variable - length sequences using a fixed - length encoding designed for preserving the anchor positions of class I peptides . |
249,732 | def sequences_to_fixed_length_index_encoded_array ( klass , sequences , left_edge = 4 , right_edge = 4 , max_length = 15 ) : result = numpy . full ( fill_value = amino_acid . AMINO_ACID_INDEX [ 'X' ] , shape = ( len ( sequences ) , max_length ) , dtype = "int32" ) df = pandas . DataFrame ( { "peptide" : sequences } ) d... | Transform a sequence of strings where each string is of length at least left_edge + right_edge and at most max_length into strings of length max_length using a scheme designed to preserve the anchor positions of class I peptides . |
249,733 | def robust_mean ( log_values ) : if log_values . shape [ 1 ] <= 3 : return numpy . nanmean ( log_values , axis = 1 ) without_nans = numpy . nan_to_num ( log_values ) mask = ( ( ~ numpy . isnan ( log_values ) ) & ( without_nans <= numpy . nanpercentile ( log_values , 75 , axis = 1 ) . reshape ( ( - 1 , 1 ) ) ) & ( witho... | Mean of values falling within the 25 - 75 percentiles . |
249,734 | def neural_networks ( self ) : result = [ ] for models in self . allele_to_allele_specific_models . values ( ) : result . extend ( models ) result . extend ( self . class1_pan_allele_models ) return result | List of the neural networks in the ensemble . |
249,735 | def merge ( cls , predictors ) : assert len ( predictors ) > 0 if len ( predictors ) == 1 : return predictors [ 0 ] allele_to_allele_specific_models = collections . defaultdict ( list ) class1_pan_allele_models = [ ] allele_to_fixed_length_sequence = predictors [ 0 ] . allele_to_fixed_length_sequence for predictor in p... | Merge the ensembles of two or more Class1AffinityPredictor instances . |
249,736 | def merge_in_place ( self , others ) : new_model_names = [ ] for predictor in others : for model in predictor . class1_pan_allele_models : model_name = self . model_name ( "pan-class1" , len ( self . class1_pan_allele_models ) ) self . class1_pan_allele_models . append ( model ) row = pandas . Series ( collections . Or... | Add the models present other predictors into the current predictor . |
249,737 | def percentile_ranks ( self , affinities , allele = None , alleles = None , throw = True ) : if allele is not None : try : transform = self . allele_to_percent_rank_transform [ allele ] return transform . transform ( affinities ) except KeyError : msg = "Allele %s has no percentile rank information" % allele if throw :... | Return percentile ranks for the given ic50 affinities and alleles . |
249,738 | def calibrate_percentile_ranks ( self , peptides = None , num_peptides_per_length = int ( 1e5 ) , alleles = None , bins = None ) : if bins is None : bins = to_ic50 ( numpy . linspace ( 1 , 0 , 1000 ) ) if alleles is None : alleles = self . supported_alleles if peptides is None : peptides = [ ] lengths = range ( self . ... | Compute the cumulative distribution of ic50 values for a set of alleles over a large universe of random peptides to enable computing quantiles in this distribution later . |
249,739 | def filter_networks ( self , predicate ) : allele_to_allele_specific_models = { } for ( allele , models ) in self . allele_to_allele_specific_models . items ( ) : allele_to_allele_specific_models [ allele ] = [ m for m in models if predicate ( m ) ] class1_pan_allele_models = [ m for m in self . class1_pan_allele_model... | Return a new Class1AffinityPredictor containing a subset of this predictor s neural networks . |
249,740 | def model_select ( self , score_function , alleles = None , min_models = 1 , max_models = 10000 ) : if alleles is None : alleles = self . supported_alleles dfs = [ ] allele_to_allele_specific_models = { } for allele in alleles : df = pandas . DataFrame ( { 'model' : self . allele_to_allele_specific_models [ allele ] } ... | Perform model selection using a user - specified scoring function . |
249,741 | def to_series ( self ) : return pandas . Series ( self . cdf , index = [ numpy . nan ] + list ( self . bin_edges ) + [ numpy . nan ] ) | Serialize the fit to a pandas . Series . |
249,742 | def get_default_class1_models_dir ( test_exists = True ) : if _MHCFLURRY_DEFAULT_CLASS1_MODELS_DIR : result = join ( get_downloads_dir ( ) , _MHCFLURRY_DEFAULT_CLASS1_MODELS_DIR ) if test_exists and not exists ( result ) : raise IOError ( "No such directory: %s" % result ) return result else : return get_path ( "models... | Return the absolute path to the default class1 models dir . |
249,743 | def get_current_release_downloads ( ) : downloads = ( get_downloads_metadata ( ) [ 'releases' ] [ get_current_release ( ) ] [ 'downloads' ] ) return OrderedDict ( ( download [ "name" ] , { 'downloaded' : exists ( join ( get_downloads_dir ( ) , download [ "name" ] ) ) , 'metadata' : download , } ) for download in downlo... | Return a dict of all available downloads in the current release . |
249,744 | def get_path ( download_name , filename = '' , test_exists = True ) : assert '/' not in download_name , "Invalid download: %s" % download_name path = join ( get_downloads_dir ( ) , download_name , filename ) if test_exists and not exists ( path ) : raise RuntimeError ( "Missing MHCflurry downloadable file: %s. " "To do... | Get the local path to a file in a MHCflurry download |
249,745 | def configure ( ) : global _DOWNLOADS_DIR global _CURRENT_RELEASE _CURRENT_RELEASE = None _DOWNLOADS_DIR = environ . get ( "MHCFLURRY_DOWNLOADS_DIR" ) if not _DOWNLOADS_DIR : metadata = get_downloads_metadata ( ) _CURRENT_RELEASE = environ . get ( "MHCFLURRY_DOWNLOADS_CURRENT_RELEASE" ) if not _CURRENT_RELEASE : _CURRE... | Setup various global variables based on environment variables . |
249,746 | def make_worker_pool ( processes = None , initializer = None , initializer_kwargs_per_process = None , max_tasks_per_worker = None ) : if not processes : processes = cpu_count ( ) pool_kwargs = { 'processes' : processes , } if max_tasks_per_worker : pool_kwargs [ "maxtasksperchild" ] = max_tasks_per_worker if initializ... | Convenience wrapper to create a multiprocessing . Pool . |
249,747 | def calibrate_percentile_ranks ( allele , predictor , peptides = None ) : global GLOBAL_DATA if peptides is None : peptides = GLOBAL_DATA [ "calibration_peptides" ] predictor . calibrate_percentile_ranks ( peptides = peptides , alleles = [ allele ] ) return { allele : predictor . allele_to_percent_rank_transform [ alle... | Private helper function . |
249,748 | def set_keras_backend ( backend = None , gpu_device_nums = None , num_threads = None ) : os . environ [ "KERAS_BACKEND" ] = "tensorflow" original_backend = backend if not backend : backend = "tensorflow-default" if gpu_device_nums is not None : os . environ [ "CUDA_VISIBLE_DEVICES" ] = "," . join ( [ str ( i ) for i in... | Configure Keras backend to use GPU or CPU . Only tensorflow is supported . |
249,749 | def uproot ( tree ) : uprooted = tree . copy ( ) uprooted . parent = None for child in tree . all_children ( ) : uprooted . add_general_child ( child ) return uprooted | Take a subranch of a tree and deep - copy the children of this subbranch into a new LabeledTree |
249,750 | def copy ( self ) : return LabeledTree ( udepth = self . udepth , depth = self . depth , text = self . text , label = self . label , children = self . children . copy ( ) if self . children != None else [ ] , parent = self . parent ) | Deep Copy of a LabeledTree |
249,751 | def add_child ( self , child ) : self . children . append ( child ) child . parent = self self . udepth = max ( [ child . udepth for child in self . children ] ) + 1 | Adds a branch to the current tree . |
249,752 | def lowercase ( self ) : if len ( self . children ) > 0 : for child in self . children : child . lowercase ( ) else : self . text = self . text . lower ( ) | Lowercase all strings in this tree . Works recursively and in - place . |
249,753 | def inject_visualization_javascript ( tree_width = 1200 , tree_height = 400 , tree_node_radius = 10 ) : from . javascript import insert_sentiment_markup insert_sentiment_markup ( tree_width = tree_width , tree_height = tree_height , tree_node_radius = tree_node_radius ) | In an Ipython notebook show SST trees using the same Javascript code as used by Jason Chuang s visualisations . |
249,754 | def create_tree_from_string ( line ) : depth = 0 current_word = "" root = None current_node = root for char in line : if char == '(' : if current_node is not None and len ( current_word ) > 0 : attribute_text_label ( current_node , current_word ) current_word = "" depth += 1 if depth > 1 : child = LabeledTree ( depth =... | Parse and convert a string representation of an example into a LabeledTree datastructure . |
249,755 | def import_tree_corpus ( path ) : tree_list = LabeledTreeCorpus ( ) with codecs . open ( path , "r" , "UTF-8" ) as f : for line in f : tree_list . append ( create_tree_from_string ( line ) ) return tree_list | Import a text file of treebank trees . |
249,756 | def load_sst ( path = None , url = 'http://nlp.stanford.edu/sentiment/trainDevTestTrees_PTB.zip' ) : if path is None : path = os . path . expanduser ( "~/stanford_sentiment_treebank/" ) makedirs ( path , exist_ok = True ) fnames = download_sst ( path , url ) return { key : import_tree_corpus ( value ) for key , value i... | Download and read in the Stanford Sentiment Treebank dataset into a dictionary with a train dev and test keys . The dictionary keys point to lists of LabeledTrees . |
249,757 | def labels ( self ) : labelings = OrderedDict ( ) for tree in self : for label , line in tree . to_labeled_lines ( ) : labelings [ line ] = label return labelings | Construct a dictionary of string - > labels |
249,758 | def to_file ( self , path , mode = "w" ) : with open ( path , mode = mode ) as f : for tree in self : for label , line in tree . to_labeled_lines ( ) : f . write ( line + "\n" ) | Save the corpus to a text file in the original format . |
249,759 | def import_tree_corpus ( labels_path , parents_path , texts_path ) : with codecs . open ( labels_path , "r" , "UTF-8" ) as f : label_lines = f . readlines ( ) with codecs . open ( parents_path , "r" , "UTF-8" ) as f : parent_lines = f . readlines ( ) with codecs . open ( texts_path , "r" , "UTF-8" ) as f : word_lines =... | Import dataset from the TreeLSTM data generation scrips . |
249,760 | def assign_texts ( node , words , next_idx = 0 ) : if len ( node . children ) == 0 : node . text = words [ next_idx ] return next_idx + 1 else : for child in node . children : next_idx = assign_texts ( child , words , next_idx ) return next_idx | Recursively assign the words to nodes by finding and assigning strings to the leaves of a tree in left to right order . |
249,761 | def read_tree ( parents , labels , words ) : trees = { } root = None for i in range ( 1 , len ( parents ) + 1 ) : if not i in trees and parents [ i - 1 ] != - 1 : idx = i prev = None while True : parent = parents [ idx - 1 ] if parent == - 1 : break tree = LabeledTree ( ) if prev is not None : tree . add_child ( prev )... | Take as input a list of integers for parents and labels along with a list of words and reconstruct a LabeledTree . |
249,762 | def set_initial_status ( self , configuration = None ) : super ( CognitiveOpDynModel , self ) . set_initial_status ( configuration ) for node in self . status : self . status [ node ] = np . random . random_sample ( ) self . initial_status = self . status . copy ( ) self . params [ 'nodes' ] [ 'cognitive' ] = { } T_ran... | Override behaviour of methods in class DiffusionModel . Overwrites initial status using random real values . Generates random node profiles . |
249,763 | def add_node_configuration ( self , param_name , node_id , param_value ) : if param_name not in self . config [ 'nodes' ] : self . config [ 'nodes' ] [ param_name ] = { node_id : param_value } else : self . config [ 'nodes' ] [ param_name ] [ node_id ] = param_value | Set a parameter for a given node |
249,764 | def add_node_set_configuration ( self , param_name , node_to_value ) : for nid , val in future . utils . iteritems ( node_to_value ) : self . add_node_configuration ( param_name , nid , val ) | Set Nodes parameter |
249,765 | def add_edge_configuration ( self , param_name , edge , param_value ) : if param_name not in self . config [ 'edges' ] : self . config [ 'edges' ] [ param_name ] = { edge : param_value } else : self . config [ 'edges' ] [ param_name ] [ edge ] = param_value | Set a parameter for a given edge |
249,766 | def add_edge_set_configuration ( self , param_name , edge_to_value ) : for edge , val in future . utils . iteritems ( edge_to_value ) : self . add_edge_configuration ( param_name , edge , val ) | Set Edges parameter |
249,767 | def multi_runs ( model , execution_number = 1 , iteration_number = 50 , infection_sets = None , nprocesses = multiprocessing . cpu_count ( ) ) : if nprocesses > multiprocessing . cpu_count ( ) : nprocesses = multiprocessing . cpu_count ( ) executions = [ ] if infection_sets is not None : if len ( infection_sets ) != ex... | Multiple executions of a given model varying the initial set of infected nodes |
249,768 | def __execute ( model , iteration_number ) : iterations = model . iteration_bunch ( iteration_number , False ) trends = model . build_trends ( iterations ) [ 0 ] del iterations del model return trends | Execute a simulation model |
249,769 | def set_initial_status ( self , configuration = None ) : super ( AlgorithmicBiasModel , self ) . set_initial_status ( configuration ) for node in self . status : self . status [ node ] = np . random . random_sample ( ) self . initial_status = self . status . copy ( ) | Override behaviour of methods in class DiffusionModel . Overwrites initial status using random real values . |
249,770 | def names ( self ) : if self . name == self . UNKNOWN_HUMAN_PLAYER : return "" , "" if not self . is_ai and " " in self . name : return "" , self . name return self . name , "" | Returns the player s name and real name . Returns two empty strings if the player is unknown . AI real name is always an empty string . |
249,771 | def _getgroup ( string , depth ) : out , comma = [ ] , False while string : items , string = _getitem ( string , depth ) if not string : break out += items if string [ 0 ] == '}' : if comma : return out , string [ 1 : ] return [ '{' + a + '}' for a in out ] , string [ 1 : ] if string [ 0 ] == ',' : comma , string = Tru... | Get a group from the string where group is a list of all the comma separated substrings up to the next } char or the brace enclosed substring if there is no comma |
249,772 | def filter_noexpand_columns ( columns ) : prefix_len = len ( NOEXPAND_PREFIX ) noexpand = [ c [ prefix_len : ] for c in columns if c . startswith ( NOEXPAND_PREFIX ) ] other = [ c for c in columns if not c . startswith ( NOEXPAND_PREFIX ) ] return other , noexpand | Return columns not containing and containing the noexpand prefix . |
249,773 | def to_root ( df , path , key = 'my_ttree' , mode = 'w' , store_index = True , * args , ** kwargs ) : if mode == 'a' : mode = 'update' elif mode == 'w' : mode = 'recreate' else : raise ValueError ( 'Unknown mode: {}. Must be "a" or "w".' . format ( mode ) ) from root_numpy import array2tree df_ = df . copy ( deep = Fal... | Write DataFrame to a ROOT file . |
249,774 | def run ( self , symbol : str ) -> SecurityDetailsViewModel : from pydatum import Datum svc = self . _svc sec_agg = svc . securities . get_aggregate_for_symbol ( symbol ) model = SecurityDetailsViewModel ( ) model . symbol = sec_agg . security . namespace + ":" + sec_agg . security . mnemonic model . security = sec_agg... | Loads the model for security details |
249,775 | def handle_friday ( next_date : Datum , period : str , mult : int , start_date : Datum ) : assert isinstance ( next_date , Datum ) assert isinstance ( start_date , Datum ) tmp_sat = next_date . clone ( ) tmp_sat . add_days ( 1 ) tmp_sun = next_date . clone ( ) tmp_sun . add_days ( 2 ) if period == RecurrencePeriod . EN... | Extracted the calculation for when the next_day is Friday |
249,776 | def get_next_occurrence ( self ) -> date : result = get_next_occurrence ( self . transaction ) assert isinstance ( result , date ) return result | Returns the next occurrence date for transaction |
249,777 | def get_enabled ( self ) -> List [ ScheduledTransaction ] : query = ( self . query . filter ( ScheduledTransaction . enabled == True ) ) return query . all ( ) | Returns only enabled scheduled transactions |
249,778 | def get_by_id ( self , tx_id : str ) -> ScheduledTransaction : return self . query . filter ( ScheduledTransaction . guid == tx_id ) . first ( ) | Fetches a tx by id |
249,779 | def get_aggregate_by_id ( self , tx_id : str ) -> ScheduledTxAggregate : tran = self . get_by_id ( tx_id ) return self . get_aggregate_for ( tran ) | Creates an aggregate for single entity |
249,780 | def get_avg_price_stat ( self ) -> Decimal : avg_price = Decimal ( 0 ) price_total = Decimal ( 0 ) price_count = 0 for account in self . security . accounts : if account . type == AccountType . TRADING . name : continue for split in account . splits : if split . quantity == 0 : continue price = split . value / split . ... | Calculates the statistical average price for the security by averaging only the prices paid . Very simple first implementation . |
249,781 | def get_avg_price_fifo ( self ) -> Decimal : balance = self . get_quantity ( ) if not balance : return Decimal ( 0 ) paid = Decimal ( 0 ) accounts = self . get_holding_accounts ( ) for account in accounts : splits = self . get_available_splits_for_account ( account ) for split in splits : paid += split . value avg_pric... | Calculates the average price paid for the security . security = Commodity Returns Decimal value . |
249,782 | def get_available_splits_for_account ( self , account : Account ) -> List [ Split ] : available_splits = [ ] query = ( self . get_splits_query ( ) . filter ( Split . account == account ) ) buy_splits = ( query . filter ( Split . quantity > 0 ) . join ( Transaction ) . order_by ( desc ( Transaction . post_date ) ) ) . a... | Returns all unused splits in the account . Used for the calculation of avg . price . The split that has been partially used will have its quantity reduced to available quantity only . |
249,783 | def get_num_shares ( self ) -> Decimal : from pydatum import Datum today = Datum ( ) . today ( ) return self . get_num_shares_on ( today ) | Returns the number of shares at this time |
249,784 | def get_last_available_price ( self ) -> PriceModel : price_db = PriceDbApplication ( ) symbol = SecuritySymbol ( self . security . namespace , self . security . mnemonic ) result = price_db . get_latest_price ( symbol ) return result | Finds the last available price for security . Uses PriceDb . |
249,785 | def __get_holding_accounts_query ( self ) : query = ( self . book . session . query ( Account ) . filter ( Account . commodity == self . security ) . filter ( Account . type != AccountType . trading . value ) ) return query | Returns all holding accounts except Trading accounts . |
249,786 | def get_income_accounts ( self ) -> List [ Account ] : query = ( self . book . session . query ( Account ) . join ( Commodity ) . filter ( Account . name == self . security . mnemonic ) . filter ( Commodity . namespace == "CURRENCY" ) . filter ( Account . type == AccountType . income . value ) ) return query . all ( ) | Returns all income accounts for this security . Income accounts are accounts not under Trading expressed in currency and having the same name as the mnemonic . They should be under Assets but this requires a recursive SQL query . |
249,787 | def get_income_total ( self ) -> Decimal : accounts = self . get_income_accounts ( ) income = Decimal ( 0 ) for acct in accounts : income += acct . get_balance ( ) return income | Sum of all income = sum of balances of all income accounts . |
249,788 | def get_income_in_period ( self , start : datetime , end : datetime ) -> Decimal : accounts = self . get_income_accounts ( ) income = Decimal ( 0 ) for acct in accounts : acc_agg = AccountAggregate ( self . book , acct ) acc_bal = acc_agg . get_balance_in_period ( start , end ) income += acc_bal return income | Returns all income in the given period |
249,789 | def get_prices ( self ) -> List [ PriceModel ] : from pricedb . dal import Price pricedb = PriceDbApplication ( ) repo = pricedb . get_price_repository ( ) query = ( repo . query ( Price ) . filter ( Price . namespace == self . security . namespace ) . filter ( Price . symbol == self . security . mnemonic ) . orderby_d... | Returns all available prices for security |
249,790 | def get_quantity ( self ) -> Decimal : from pydatum import Datum today = Datum ( ) today . today ( ) today . end_of_day ( ) return self . get_num_shares_on ( today . value ) | Returns the number of shares for the given security . It gets the number from all the accounts in the book . |
249,791 | def get_splits_query ( self ) : query = ( self . book . session . query ( Split ) . join ( Account ) . filter ( Account . type != AccountType . trading . value ) . filter ( Account . commodity_guid == self . security . guid ) ) return query | Returns the query for all splits for this security |
249,792 | def get_total_paid ( self ) -> Decimal : query = ( self . get_splits_query ( ) ) splits = query . all ( ) total = Decimal ( 0 ) for split in splits : total += split . value return total | Returns the total amount paid in currency for the stocks owned |
249,793 | def get_total_paid_for_remaining_stock ( self ) -> Decimal : paid = Decimal ( 0 ) accounts = self . get_holding_accounts ( ) for acc in accounts : splits = self . get_available_splits_for_account ( acc ) paid += sum ( split . value for split in splits ) return paid | Returns the amount paid only for the remaining stock |
249,794 | def get_value ( self ) -> Decimal : quantity = self . get_quantity ( ) price = self . get_last_available_price ( ) if not price : return Decimal ( 0 ) value = quantity * price . value return value | Returns the current value of stocks |
249,795 | def get_value_in_base_currency ( self ) -> Decimal : amt_orig = self . get_value ( ) sec_cur = self . get_currency ( ) cur_svc = CurrenciesAggregate ( self . book ) base_cur = cur_svc . get_default_currency ( ) if sec_cur == base_cur : return amt_orig single_svc = cur_svc . get_currency_aggregate ( sec_cur ) rate = sin... | Calculates the value of security holdings in base currency |
249,796 | def accounts ( self ) -> List [ Account ] : result = ( [ acct for acct in self . security . accounts if acct . fullname . startswith ( 'Assets' ) ] ) return result | Returns the asset accounts in which the security is held |
249,797 | def find ( self , search_term : str ) -> List [ Commodity ] : query = ( self . query . filter ( Commodity . mnemonic . like ( '%' + search_term + '%' ) | Commodity . fullname . like ( '%' + search_term + '%' ) ) ) return query . all ( ) | Searches for security by part of the name |
249,798 | def get_all ( self ) -> List [ Commodity ] : query = ( self . query . order_by ( Commodity . namespace , Commodity . mnemonic ) ) return query . all ( ) | Loads all non - currency commodities assuming they are stocks . |
249,799 | def get_by_symbol ( self , symbol : str ) -> Commodity : full_symbol = self . __parse_gc_symbol ( symbol ) query = ( self . query . filter ( Commodity . mnemonic == full_symbol [ "mnemonic" ] ) ) if full_symbol [ "namespace" ] : query = query . filter ( Commodity . namespace == full_symbol [ "namespace" ] ) return quer... | Returns the commodity with the given symbol . If more are found an exception will be thrown . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.