idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
11,000
def get_balance ( self ) : if not SMSGLOBAL_CHECK_BALANCE_COUNTRY : raise Exception ( 'SMSGLOBAL_CHECK_BALANCE_COUNTRY setting must be set to check balance.' ) params = { 'user' : self . get_username ( ) , 'password' : self . get_password ( ) , 'country' : SMSGLOBAL_CHECK_BALANCE_COUNTRY , } req = urllib2 . Request ( S...
Get balance with provider .
11,001
def send_messages ( self , sms_messages ) : if not sms_messages : return num_sent = 0 for message in sms_messages : if self . _send ( message ) : num_sent += 1 return num_sent
Sends one or more SmsMessage objects and returns the number of sms messages sent .
11,002
def send_sms ( body , from_phone , to , flash = False , fail_silently = False , auth_user = None , auth_password = None , connection = None ) : from sendsms . message import SmsMessage connection = connection or get_connection ( username = auth_user , password = auth_password , fail_silently = fail_silently ) return Sm...
Easy wrapper for send a single SMS to a recipient list .
11,003
def open ( self ) : self . client = SmsGateApi ( getattr ( settings , 'SMS_SLUZBA_API_LOGIN' , '' ) , getattr ( settings , 'SMS_SLUZBA_API_PASSWORD' , '' ) , getattr ( settings , 'SMS_SLUZBA_API_TIMEOUT' , 2 ) , getattr ( settings , 'SMS_SLUZBA_API_USE_SSL' , True ) )
Initializes sms . sluzba . cz API library .
11,004
def send_messages ( self , messages ) : count = 0 for message in messages : message_body = unicodedata . normalize ( 'NFKD' , unicode ( message . body ) ) . encode ( 'ascii' , 'ignore' ) for tel_number in message . to : try : self . client . send ( tel_number , message_body , getattr ( settings , 'SMS_SLUZBA_API_USE_PO...
Sending SMS messages via sms . sluzba . cz API .
11,005
def _send ( self , message ) : params = { 'EsendexUsername' : self . get_username ( ) , 'EsendexPassword' : self . get_password ( ) , 'EsendexAccount' : self . get_account ( ) , 'EsendexOriginator' : message . from_phone , 'EsendexRecipient' : "," . join ( message . to ) , 'EsendexBody' : message . body , 'EsendexPlain...
Private method to send one message .
11,006
def send ( self , fail_silently = False ) : if not self . to : return 0 res = self . get_connection ( fail_silently ) . send_messages ( [ self ] ) sms_post_send . send ( sender = self , to = self . to , from_phone = self . from_phone , body = self . body ) return res
Sends the sms message
11,007
def _send ( self , message ) : params = { 'from' : message . from_phone , 'to' : "," . join ( message . to ) , 'text' : message . body , 'api_key' : self . get_api_key ( ) , 'api_secret' : self . get_api_secret ( ) , } print ( params ) logger . debug ( "POST to %r with body: %r" , NEXMO_API_URL , params ) return self ....
A helper method that does the actual sending
11,008
def get_market_summary ( self , market ) : return self . _api_query ( path_dict = { API_V1_1 : '/public/getmarketsummary' , API_V2_0 : '/pub/Market/GetMarketSummary' } , options = { 'market' : market , 'marketname' : market } , protection = PROTECTION_PUB )
Used to get the last 24 hour summary of all active exchanges in specific coin
11,009
def get_orderbook ( self , market , depth_type = BOTH_ORDERBOOK ) : return self . _api_query ( path_dict = { API_V1_1 : '/public/getorderbook' , API_V2_0 : '/pub/Market/GetMarketOrderBook' } , options = { 'market' : market , 'marketname' : market , 'type' : depth_type } , protection = PROTECTION_PUB )
Used to get retrieve the orderbook for a given market .
11,010
def get_market_history ( self , market ) : return self . _api_query ( path_dict = { API_V1_1 : '/public/getmarkethistory' , } , options = { 'market' : market , 'marketname' : market } , protection = PROTECTION_PUB )
Used to retrieve the latest trades that have occurred for a specific market .
11,011
def buy_limit ( self , market , quantity , rate ) : return self . _api_query ( path_dict = { API_V1_1 : '/market/buylimit' , } , options = { 'market' : market , 'quantity' : quantity , 'rate' : rate } , protection = PROTECTION_PRV )
Used to place a buy order in a specific market . Use buylimit to place limit orders Make sure you have the proper permissions set on your API keys for this call to work
11,012
def get_open_orders ( self , market = None ) : return self . _api_query ( path_dict = { API_V1_1 : '/market/getopenorders' , API_V2_0 : '/key/market/getopenorders' } , options = { 'market' : market , 'marketname' : market } if market else None , protection = PROTECTION_PRV )
Get all orders that you currently have opened . A specific market can be requested .
11,013
def get_deposit_address ( self , currency ) : return self . _api_query ( path_dict = { API_V1_1 : '/account/getdepositaddress' , API_V2_0 : '/key/balance/getdepositaddress' } , options = { 'currency' : currency , 'currencyname' : currency } , protection = PROTECTION_PRV )
Used to generate or retrieve an address for a specific currency
11,014
def withdraw ( self , currency , quantity , address , paymentid = None ) : options = { 'currency' : currency , 'quantity' : quantity , 'address' : address } if paymentid : options [ 'paymentid' ] = paymentid return self . _api_query ( path_dict = { API_V1_1 : '/account/withdraw' , API_V2_0 : '/key/balance/withdrawcurre...
Used to withdraw funds from your account
11,015
def get_order_history ( self , market = None ) : if market : return self . _api_query ( path_dict = { API_V1_1 : '/account/getorderhistory' , API_V2_0 : '/key/market/GetOrderHistory' } , options = { 'market' : market , 'marketname' : market } , protection = PROTECTION_PRV ) else : return self . _api_query ( path_dict =...
Used to retrieve order trade history of account
11,016
def get_order ( self , uuid ) : return self . _api_query ( path_dict = { API_V1_1 : '/account/getorder' , API_V2_0 : '/key/orders/getorder' } , options = { 'uuid' : uuid , 'orderid' : uuid } , protection = PROTECTION_PRV )
Used to get details of buy or sell order
11,017
def list_markets_by_currency ( self , currency ) : return [ market [ 'MarketName' ] for market in self . get_markets ( ) [ 'result' ] if market [ 'MarketName' ] . lower ( ) . endswith ( currency . lower ( ) ) ]
Helper function to see which markets exist for a currency .
11,018
def get_pending_withdrawals ( self , currency = None ) : return self . _api_query ( path_dict = { API_V2_0 : '/key/balance/getpendingwithdrawals' } , options = { 'currencyname' : currency } if currency else None , protection = PROTECTION_PRV )
Used to view your pending withdrawals
11,019
def get_candles ( self , market , tick_interval ) : return self . _api_query ( path_dict = { API_V2_0 : '/pub/market/GetTicks' } , options = { 'marketName' : market , 'tickInterval' : tick_interval } , protection = PROTECTION_PUB )
Used to get all tick candles for a market .
11,020
def changelist_view ( self , request , extra_context = None ) : if extra_context is None : extra_context = { } response = self . adv_filters_handle ( request , extra_context = extra_context ) if response : return response return super ( AdminAdvancedFiltersMixin , self ) . changelist_view ( request , extra_context = ex...
Add advanced_filters form to changelist context
11,021
def query ( self ) : if not self . b64_query : return None s = QSerializer ( base64 = True ) return s . loads ( self . b64_query )
De - serialize decode and return an ORM query stored in b64_query .
11,022
def query ( self , value ) : if not isinstance ( value , Q ) : raise Exception ( 'Must only be passed a Django (Q)uery object' ) s = QSerializer ( base64 = True ) self . b64_query = s . dumps ( value )
Serialize an ORM query Base - 64 encode it and set it to the b64_query field
11,023
def _build_field_choices ( self , fields ) : return tuple ( sorted ( [ ( fquery , capfirst ( fname ) ) for fquery , fname in fields . items ( ) ] , key = lambda f : f [ 1 ] . lower ( ) ) ) + self . FIELD_CHOICES
Iterate over passed model fields tuple and update initial choices .
11,024
def _parse_query_dict ( query_data , model ) : operator = 'iexact' if query_data [ 'field' ] == '_OR' : query_data [ 'operator' ] = operator return query_data parts = query_data [ 'field' ] . split ( '__' ) if len ( parts ) < 2 : field = parts [ 0 ] else : if parts [ - 1 ] in dict ( AdvancedFilterQueryForm . OPERATORS ...
Take a list of query field dict and return data for form initialization
11,025
def set_range_value ( self , data ) : dtfrom = data . pop ( 'value_from' ) dtto = data . pop ( 'value_to' ) if dtfrom is dtto is None : self . errors [ 'value' ] = [ 'Date range requires values' ] raise forms . ValidationError ( [ ] ) data [ 'value' ] = ( dtfrom , dtto )
Validates date range by parsing into 2 datetime objects and validating them both .
11,026
def make_query ( self , * args , ** kwargs ) : query = Q ( ) query_dict = self . _build_query_dict ( self . cleaned_data ) if 'negate' in self . cleaned_data and self . cleaned_data [ 'negate' ] : query = query & ~ Q ( ** query_dict ) else : query = query & Q ( ** query_dict ) return query
Returns a Q object from the submitted form
11,027
def generate_query ( self ) : query = Q ( ) ORed = [ ] for form in self . _non_deleted_forms : if not hasattr ( form , 'cleaned_data' ) : continue if form . cleaned_data [ 'field' ] == "_OR" : ORed . append ( query ) query = Q ( ) else : query = query & form . make_query ( ) if ORed : if query : ORed . append ( query )...
Reduces multiple queries into a single usable query
11,028
def initialize_form ( self , instance , model , data = None , extra = None ) : model_fields = self . get_fields_from_model ( model , self . _filter_fields ) forms = [ ] if instance : for field_data in instance . list_fields ( ) : forms . append ( AdvancedFilterQueryForm . _parse_query_dict ( field_data , model ) ) form...
Takes a finalized query and generate it s form data
11,029
def login ( ) : cas_token_session_key = current_app . config [ 'CAS_TOKEN_SESSION_KEY' ] redirect_url = create_cas_login_url ( current_app . config [ 'CAS_SERVER' ] , current_app . config [ 'CAS_LOGIN_ROUTE' ] , flask . url_for ( '.login' , origin = flask . session . get ( 'CAS_AFTER_LOGIN_SESSION_URL' ) , _external = ...
This route has two purposes . First it is used by the user to login . Second it is used by the CAS to respond with the ticket after the user logs in successfully .
11,030
def logout ( ) : cas_username_session_key = current_app . config [ 'CAS_USERNAME_SESSION_KEY' ] cas_attributes_session_key = current_app . config [ 'CAS_ATTRIBUTES_SESSION_KEY' ] if cas_username_session_key in flask . session : del flask . session [ cas_username_session_key ] if cas_attributes_session_key in flask . se...
When the user accesses this route they are logged out .
11,031
def validate ( ticket ) : cas_username_session_key = current_app . config [ 'CAS_USERNAME_SESSION_KEY' ] cas_attributes_session_key = current_app . config [ 'CAS_ATTRIBUTES_SESSION_KEY' ] current_app . logger . debug ( "validating token {0}" . format ( ticket ) ) cas_validate_url = create_cas_validate_url ( current_app...
Will attempt to validate the ticket . If validation fails then False is returned . If validation is successful then True is returned and the validated username is saved in the session under the key CAS_USERNAME_SESSION_KEY while tha validated attributes dictionary is saved under the key CAS_ATTRIBUTES_SESSION_KEY .
11,032
def create_url ( base , path = None , * query ) : url = base if path is not None : url = urljoin ( url , quote ( path ) ) query = filter ( lambda pair : pair [ 1 ] is not None , query ) url = urljoin ( url , '?{0}' . format ( urlencode ( list ( query ) ) ) ) return url
Create a url .
11,033
def create_cas_login_url ( cas_url , cas_route , service , renew = None , gateway = None ) : return create_url ( cas_url , cas_route , ( 'service' , service ) , ( 'renew' , renew ) , ( 'gateway' , gateway ) , )
Create a CAS login URL .
11,034
def create_cas_validate_url ( cas_url , cas_route , service , ticket , renew = None ) : return create_url ( cas_url , cas_route , ( 'service' , service ) , ( 'ticket' , ticket ) , ( 'renew' , renew ) , )
Create a CAS validate URL .
11,035
def namespace_to_dict ( obj ) : if isinstance ( obj , ( argparse . Namespace , optparse . Values ) ) : return vars ( obj ) return obj
If obj is argparse . Namespace or optparse . Values we ll return a dict representation of it else return the original object .
11,036
def xdg_config_dirs ( ) : paths = [ ] if 'XDG_CONFIG_HOME' in os . environ : paths . append ( os . environ [ 'XDG_CONFIG_HOME' ] ) if 'XDG_CONFIG_DIRS' in os . environ : paths . extend ( os . environ [ 'XDG_CONFIG_DIRS' ] . split ( ':' ) ) else : paths . append ( '/etc/xdg' ) paths . append ( '/etc' ) return paths
Returns a list of paths taken from the XDG_CONFIG_DIRS and XDG_CONFIG_HOME environment varibables if they exist
11,037
def config_dirs ( ) : paths = [ ] if platform . system ( ) == 'Darwin' : paths . append ( MAC_DIR ) paths . append ( UNIX_DIR_FALLBACK ) paths . extend ( xdg_config_dirs ( ) ) elif platform . system ( ) == 'Windows' : paths . append ( WINDOWS_DIR_FALLBACK ) if WINDOWS_DIR_VAR in os . environ : paths . append ( os . env...
Return a platform - specific list of candidates for user configuration directories on the system .
11,038
def load_yaml ( filename ) : try : with open ( filename , 'rb' ) as f : return yaml . load ( f , Loader = Loader ) except ( IOError , yaml . error . YAMLError ) as exc : raise ConfigReadError ( filename , exc )
Read a YAML document from a file . If the file cannot be read or parsed a ConfigReadError is raised .
11,039
def as_template ( value ) : if isinstance ( value , Template ) : return value elif isinstance ( value , abc . Mapping ) : return MappingTemplate ( value ) elif value is int : return Integer ( ) elif isinstance ( value , int ) : return Integer ( value ) elif isinstance ( value , type ) and issubclass ( value , BASESTRIN...
Convert a simple shorthand Python value to a Template .
11,040
def of ( cls , value ) : if isinstance ( value , ConfigSource ) : return value elif isinstance ( value , dict ) : return ConfigSource ( value ) else : raise TypeError ( u'source value must be a dict' )
Given either a dictionary or a ConfigSource object return a ConfigSource object . This lets a function accept either type of object as an argument .
11,041
def _build_namespace_dict ( cls , obj , dots = False ) : obj = namespace_to_dict ( obj ) if not isinstance ( obj , dict ) : return obj keys = obj . keys ( ) if PY3 else obj . iterkeys ( ) if dots : keys = sorted ( list ( keys ) ) output = { } for key in keys : value = obj [ key ] if value is None : continue save_to = o...
Recursively replaces all argparse . Namespace and optparse . Values with dicts and drops any keys with None values .
11,042
def set_args ( self , namespace , dots = False ) : self . set ( self . _build_namespace_dict ( namespace , dots ) )
Overlay parsed command - line arguments generated by a library like argparse or optparse onto this view s value .
11,043
def flatten ( self , redact = False ) : od = OrderedDict ( ) for key , view in self . items ( ) : if redact and view . redact : od [ key ] = REDACTED_TOMBSTONE else : try : od [ key ] = view . flatten ( redact = redact ) except ConfigTypeError : od [ key ] = view . get ( ) return od
Create a hierarchy of OrderedDicts containing the data from this view recursively reifying all views to get their represented values .
11,044
def represent_bool ( self , data ) : if data : value = u'yes' else : value = u'no' return self . represent_scalar ( 'tag:yaml.org,2002:bool' , value )
Represent bool as yes or no instead of true or false .
11,045
def _add_default_source ( self ) : if self . modname : if self . _package_path : filename = os . path . join ( self . _package_path , DEFAULT_FILENAME ) if os . path . isfile ( filename ) : self . add ( ConfigSource ( load_yaml ( filename ) , filename , True ) )
Add the package s default configuration settings . This looks for a YAML file located inside the package for the module modname if it was given .
11,046
def read ( self , user = True , defaults = True ) : if user : self . _add_user_source ( ) if defaults : self . _add_default_source ( )
Find and read the files for this configuration and set them as the sources for this configuration . To disable either discovered user configuration files or the in - package defaults set user or defaults to False .
11,047
def set_file ( self , filename ) : filename = os . path . abspath ( filename ) self . set ( ConfigSource ( load_yaml ( filename ) , filename ) )
Parses the file as YAML and inserts it into the configuration sources with highest priority .
11,048
def dump ( self , full = True , redact = False ) : if full : out_dict = self . flatten ( redact = redact ) else : sources = [ s for s in self . sources if not s . default ] temp_root = RootView ( sources ) temp_root . redactions = self . redactions out_dict = temp_root . flatten ( redact = redact ) yaml_out = yaml . du...
Dump the Configuration object to a YAML file .
11,049
def clear ( self ) : super ( LazyConfig , self ) . clear ( ) self . _lazy_suffix = [ ] self . _lazy_prefix = [ ]
Remove all sources from this configuration .
11,050
def value ( self , view , template = None ) : if view . exists ( ) : value , _ = view . first ( ) return self . convert ( value , view ) elif self . default is REQUIRED : raise NotFoundError ( u"{0} not found" . format ( view . name ) ) else : return self . default
Get the value for a ConfigView .
11,051
def fail ( self , message , view , type_error = False ) : exc_class = ConfigTypeError if type_error else ConfigValueError raise exc_class ( u'{0}: {1}' . format ( view . name , message ) )
Raise an exception indicating that a value cannot be accepted .
11,052
def convert ( self , value , view ) : if isinstance ( value , int ) : return value elif isinstance ( value , float ) : return int ( value ) else : self . fail ( u'must be a number' , view , True )
Check that the value is an integer . Floats are rounded .
11,053
def convert ( self , value , view ) : if isinstance ( value , NUMERIC_TYPES ) : return value else : self . fail ( u'must be numeric, not {0}' . format ( type ( value ) . __name__ ) , view , True )
Check that the value is an int or a float .
11,054
def value ( self , view , template = None ) : out = AttrDict ( ) for key , typ in self . subtemplates . items ( ) : out [ key ] = typ . value ( view [ key ] , self ) return out
Get a dict with the same keys as the template and values validated according to the value types .
11,055
def value ( self , view , template = None ) : out = [ ] for item in view : out . append ( self . subtemplate . value ( item , self ) ) return out
Get a list of items validated against the template .
11,056
def convert ( self , value , view ) : if isinstance ( value , BASESTRING ) : if self . pattern and not self . regex . match ( value ) : self . fail ( u"must match the pattern {0}" . format ( self . pattern ) , view ) return value else : self . fail ( u'must be a string' , view , True )
Check that the value is a string and matches the pattern .
11,057
def convert ( self , value , view ) : is_mapping = isinstance ( self . template , MappingTemplate ) for candidate in self . allowed : try : if is_mapping : if isinstance ( candidate , Filename ) and candidate . relative_to : next_template = candidate . template_with_relatives ( view , self . template ) next_template . ...
Ensure that the value follows at least one template .
11,058
def export_live_eggs ( self , env = False ) : path_eggs = [ p for p in sys . path if p . endswith ( '.egg' ) ] command = self . get_finalized_command ( "egg_info" ) egg_base = path . abspath ( command . egg_base ) unique_path_eggs = set ( path_eggs + [ egg_base ] ) os . environ [ 'PYTHONPATH' ] = ':' . join ( unique_pa...
Adds all of the eggs in the current environment to PYTHONPATH .
11,059
def get_from_environment ( ) : name = os . environ . get ( "EXECJS_RUNTIME" , "" ) if not name : return None try : return _find_runtime_by_name ( name ) except exceptions . RuntimeUnavailableError : return None
Return the JavaScript runtime that is specified in EXECJS_RUNTIME environment variable . If EXECJS_RUNTIME environment variable is empty or invalid return None .
11,060
def split_table_cells ( self , row ) : row = iter ( row ) col = 0 start_col = col + 1 cell = '' first_cell = True while True : char = next ( row , None ) col += 1 if char == '|' : if first_cell : first_cell = False else : yield ( cell , start_col ) cell = '' start_col = col + 1 elif char == '\\' : char = next ( row ) c...
An iterator returning all the table cells in a row with their positions accounting for escaping .
11,061
def as_freq ( data_series , freq , atomic_freq = "1 Min" , series_type = "cumulative" ) : if not isinstance ( data_series , pd . Series ) : raise ValueError ( "expected series, got object with class {}" . format ( data_series . __class__ ) ) if data_series . empty : return data_series series = remove_duplicates ( data_...
Resample data to a different frequency .
11,062
def get_baseline_data ( data , start = None , end = None , max_days = 365 , allow_billing_period_overshoot = False , ignore_billing_period_gap_for_day_count = False , ) : if max_days is not None : if start is not None : raise ValueError ( "If max_days is set, start cannot be set: start={}, max_days={}." . format ( star...
Filter down to baseline period data .
11,063
def get_reporting_data ( data , start = None , end = None , max_days = 365 , allow_billing_period_overshoot = False , ignore_billing_period_gap_for_day_count = False , ) : if max_days is not None : if end is not None : raise ValueError ( "If max_days is set, end cannot be set: end={}, max_days={}." . format ( end , max...
Filter down to reporting period data .
11,064
def modeled_savings ( baseline_model , reporting_model , result_index , temperature_data , with_disaggregated = False , confidence_level = 0.90 , predict_kwargs = None , ) : prediction_index = result_index if predict_kwargs is None : predict_kwargs = { } model_type = None if isinstance ( baseline_model , CalTRACKUsageP...
Compute modeled savings i . e . savings in which baseline and reporting usage values are based on models . This is appropriate for annualizing or weather normalizing models .
11,065
def _caltrack_predict_design_matrix ( model_type , model_params , data , disaggregated = False , input_averages = False , output_averages = False , ) : zeros = pd . Series ( 0 , index = data . index ) ones = zeros + 1 if isinstance ( data . index , pd . DatetimeIndex ) : days_per_period = day_counts ( data . index ) el...
An internal CalTRACK predict method for use with a design matrix of the form used in model fitting .
11,066
def caltrack_usage_per_day_predict ( model_type , model_params , prediction_index , temperature_data , degree_day_method = "daily" , with_disaggregated = False , with_design_matrix = False , ) : if model_params is None : raise MissingModelParameterError ( "model_params is None." ) predict_warnings = [ ] cooling_balance...
CalTRACK predict method .
11,067
def get_too_few_non_zero_degree_day_warning ( model_type , balance_point , degree_day_type , degree_days , minimum_non_zero ) : warnings = [ ] n_non_zero = int ( ( degree_days > 0 ) . sum ( ) ) if n_non_zero < minimum_non_zero : warnings . append ( EEMeterWarning ( qualified_name = ( "eemeter.caltrack_daily.{model_type...
Return an empty list or a single warning wrapped in a list regarding non - zero degree days for a set of degree days .
11,068
def get_total_degree_day_too_low_warning ( model_type , balance_point , degree_day_type , avg_degree_days , period_days , minimum_total , ) : warnings = [ ] total_degree_days = ( avg_degree_days * period_days ) . sum ( ) if total_degree_days < minimum_total : warnings . append ( EEMeterWarning ( qualified_name = ( "eem...
Return an empty list or a single warning wrapped in a list regarding the total summed degree day values .
11,069
def get_parameter_negative_warning ( model_type , model_params , parameter ) : warnings = [ ] if model_params . get ( parameter , 0 ) < 0 : warnings . append ( EEMeterWarning ( qualified_name = ( "eemeter.caltrack_daily.{model_type}.{parameter}_negative" . format ( model_type = model_type , parameter = parameter ) ) , ...
Return an empty list or a single warning wrapped in a list indicating whether model parameter is negative .
11,070
def get_parameter_p_value_too_high_warning ( model_type , model_params , parameter , p_value , maximum_p_value ) : warnings = [ ] if p_value > maximum_p_value : data = { "{}_p_value" . format ( parameter ) : p_value , "{}_maximum_p_value" . format ( parameter ) : maximum_p_value , } data . update ( model_params ) warni...
Return an empty list or a single warning wrapped in a list indicating whether model parameter p - value is too high .
11,071
def get_fit_failed_candidate_model ( model_type , formula ) : warnings = [ EEMeterWarning ( qualified_name = "eemeter.caltrack_daily.{}.model_results" . format ( model_type ) , description = ( "Error encountered in statsmodels.formula.api.ols method. (Empty data?)" ) , data = { "traceback" : traceback . format_exc ( ) ...
Return a Candidate model that indicates the fitting routine failed .
11,072
def get_intercept_only_candidate_models ( data , weights_col ) : model_type = "intercept_only" formula = "meter_value ~ 1" if weights_col is None : weights = 1 else : weights = data [ weights_col ] try : model = smf . wls ( formula = formula , data = data , weights = weights ) except Exception as e : return [ get_fit_f...
Return a list of a single candidate intercept - only model .
11,073
def get_single_cdd_only_candidate_model ( data , minimum_non_zero_cdd , minimum_total_cdd , beta_cdd_maximum_p_value , weights_col , balance_point , ) : model_type = "cdd_only" cdd_column = "cdd_%s" % balance_point formula = "meter_value ~ %s" % cdd_column if weights_col is None : weights = 1 else : weights = data [ we...
Return a single candidate cdd - only model for a particular balance point .
11,074
def get_cdd_only_candidate_models ( data , minimum_non_zero_cdd , minimum_total_cdd , beta_cdd_maximum_p_value , weights_col ) : balance_points = [ int ( col [ 4 : ] ) for col in data . columns if col . startswith ( "cdd" ) ] candidate_models = [ get_single_cdd_only_candidate_model ( data , minimum_non_zero_cdd , minim...
Return a list of all possible candidate cdd - only models .
11,075
def get_single_hdd_only_candidate_model ( data , minimum_non_zero_hdd , minimum_total_hdd , beta_hdd_maximum_p_value , weights_col , balance_point , ) : model_type = "hdd_only" hdd_column = "hdd_%s" % balance_point formula = "meter_value ~ %s" % hdd_column if weights_col is None : weights = 1 else : weights = data [ we...
Return a single candidate hdd - only model for a particular balance point .
11,076
def get_single_cdd_hdd_candidate_model ( data , minimum_non_zero_cdd , minimum_non_zero_hdd , minimum_total_cdd , minimum_total_hdd , beta_cdd_maximum_p_value , beta_hdd_maximum_p_value , weights_col , cooling_balance_point , heating_balance_point , ) : model_type = "cdd_hdd" cdd_column = "cdd_%s" % cooling_balance_poi...
Return and fit a single candidate cdd_hdd model for a particular selection of cooling balance point and heating balance point
11,077
def get_cdd_hdd_candidate_models ( data , minimum_non_zero_cdd , minimum_non_zero_hdd , minimum_total_cdd , minimum_total_hdd , beta_cdd_maximum_p_value , beta_hdd_maximum_p_value , weights_col , ) : cooling_balance_points = [ int ( col [ 4 : ] ) for col in data . columns if col . startswith ( "cdd" ) ] heating_balance...
Return a list of candidate cdd_hdd models for a particular selection of cooling balance point and heating balance point
11,078
def select_best_candidate ( candidate_models ) : best_r_squared_adj = - np . inf best_candidate = None for candidate in candidate_models : if ( candidate . status == "QUALIFIED" and candidate . r_squared_adj > best_r_squared_adj ) : best_candidate = candidate best_r_squared_adj = candidate . r_squared_adj if best_candi...
Select and return the best candidate model based on r - squared and qualification .
11,079
def fit_caltrack_usage_per_day_model ( data , fit_cdd = True , use_billing_presets = False , minimum_non_zero_cdd = 10 , minimum_non_zero_hdd = 10 , minimum_total_cdd = 20 , minimum_total_hdd = 20 , beta_cdd_maximum_p_value = 1 , beta_hdd_maximum_p_value = 1 , weights_col = None , fit_intercept_only = True , fit_cdd_on...
CalTRACK daily and billing methods using a usage - per - day modeling strategy .
11,080
def plot_caltrack_candidate ( candidate , best = False , ax = None , title = None , figsize = None , temp_range = None , alpha = None , ** kwargs ) : try : import matplotlib . pyplot as plt except ImportError : raise ImportError ( "matplotlib is required for plotting." ) if figsize is None : figsize = ( 10 , 4 ) if ax ...
Plot a CalTRACK candidate model .
11,081
def plot ( self , ax = None , title = None , figsize = None , with_candidates = False , candidate_alpha = None , temp_range = None , ) : try : import matplotlib . pyplot as plt except ImportError : raise ImportError ( "matplotlib is required for plotting." ) if figsize is None : figsize = ( 10 , 4 ) if ax is None : fig...
Plot a model fit .
11,082
def plot_time_series ( meter_data , temperature_data , ** kwargs ) : try : import matplotlib . pyplot as plt except ImportError : raise ImportError ( "matplotlib is required for plotting." ) default_kwargs = { "figsize" : ( 16 , 4 ) } default_kwargs . update ( kwargs ) fig , ax1 = plt . subplots ( ** default_kwargs ) a...
Plot meter and temperature data in dual - axes time series .
11,083
def plot_energy_signature ( meter_data , temperature_data , temp_col = None , ax = None , title = None , figsize = None , ** kwargs ) : try : import matplotlib . pyplot as plt except ImportError : raise ImportError ( "matplotlib is required for plotting." ) temperature_mean = compute_temperature_features ( meter_data ....
Plot meter and temperature data in energy signature .
11,084
def meter_data_from_csv ( filepath_or_buffer , tz = None , start_col = "start" , value_col = "value" , gzipped = False , freq = None , ** kwargs ) : read_csv_kwargs = { "usecols" : [ start_col , value_col ] , "dtype" : { value_col : np . float64 } , "parse_dates" : [ start_col ] , "index_col" : start_col , } if gzipped...
Load meter data from a CSV file .
11,085
def temperature_data_from_csv ( filepath_or_buffer , tz = None , date_col = "dt" , temp_col = "tempF" , gzipped = False , freq = None , ** kwargs ) : read_csv_kwargs = { "usecols" : [ date_col , temp_col ] , "dtype" : { temp_col : np . float64 } , "parse_dates" : [ date_col ] , "index_col" : date_col , } if gzipped : r...
Load temperature data from a CSV file .
11,086
def meter_data_from_json ( data , orient = "list" ) : if orient == "list" : df = pd . DataFrame ( data , columns = [ "start" , "value" ] ) df [ "start" ] = pd . DatetimeIndex ( df . start ) . tz_localize ( "UTC" ) df = df . set_index ( "start" ) return df else : raise ValueError ( "orientation not recognized." )
Load meter data from json .
11,087
def notify ( self ) : if flask . has_request_context ( ) : emit ( _NAME + str ( self . _uuid ) ) else : sio = flask . current_app . extensions [ 'socketio' ] sio . emit ( _NAME + str ( self . _uuid ) ) eventlet . sleep ( )
Notify the client .
11,088
def validate ( key ) : if not isinstance ( key , ( str , bytes ) ) : raise KeyError ( 'Key must be of type str or bytes, found type {}' . format ( type ( key ) ) )
Check that the key is a string or bytestring .
11,089
def pack ( x : Any ) -> bytes : try : return msgpack . packb ( x , default = encoders ) except TypeError as exc : message = ( 'Serialization error, check the data passed to a do_ command. ' 'Cannot serialize this object:\n' ) + str ( exc ) [ 16 : ] raise SerializationError ( message )
Encode x into msgpack with additional encoders .
11,090
def make_event ( event : Callable ) -> Callable : @ property @ wraps ( event ) def actualevent ( self ) : name = event . __name__ [ 3 : ] try : getter = event ( self ) . __name__ except AttributeError : getter = None return Event ( name , self . _uuid , getter ) return actualevent
Create an event from a method signature .
11,091
def _insert ( wrap : str , tag : Optional [ str ] ) -> str : if tag is None : raise ValueError ( 'tag cannot be None' ) formatter = string . Formatter ( ) mapping = FormatDict ( component = tag ) return formatter . vformat ( wrap , ( ) , mapping )
Insert the component tag into the wrapper html .
11,092
def do_options ( self , labels , values ) : return [ dict ( label = l , value = v ) for l , v in zip ( labels , values ) ]
Replace the drop down fields .
11,093
def do_options ( self , labels : Sequence [ str ] , values : Sequence [ Union [ str , int ] ] ) -> Sequence [ Dict ] : return [ { 'label' : label , 'value' : value } for label , value in zip ( labels , values ) ]
Replace the checkbox options .
11,094
def do_options ( self , labels , values ) : return [ { 'label' : label , 'value' : value } for label , value in zip ( labels , values ) ]
Replace the radio button options .
11,095
def node_version ( ) : version = check_output ( ( 'node' , '--version' ) ) return tuple ( int ( x ) for x in version . strip ( ) [ 1 : ] . split ( b'.' ) )
Get node version .
11,096
def run ( self ) : ret = eventlet . spawn ( self . context ( self . func ) ) eventlet . sleep ( self . seconds ) try : ret . wait ( ) except Exception : traceback . print_exc ( ) self . thread = eventlet . spawn ( self . run )
Invoke the function repeatedly on a timer .
11,097
def overlap ( self , other : 'Span' ) : return not ( other . column_end <= self . column_start or self . column_end <= other . column_start or other . row_end <= self . row_start or self . row_end <= other . row_start )
Detect if two spans overlap .
11,098
def cells ( self ) -> Generator [ Tuple [ int , int ] , None , None ] : yield from itertools . product ( range ( self . row_start , self . row_end ) , range ( self . column_start , self . column_end ) )
Generate cells in span .
11,099
def pixels ( self , value : float ) -> 'Size' : raise_not_number ( value ) self . maximum = '{}px' . format ( value ) return self
Set the size in pixels .