idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
248,800 | def get_by_symbol ( self , symbol : str ) -> Commodity : # handle namespace. Accept GnuCash and Yahoo-style symbols. 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 query . first ( ) | Returns the commodity with the given symbol . If more are found an exception will be thrown . | 120 | 18 |
248,801 | def get_stocks ( self , symbols : List [ str ] ) -> List [ Commodity ] : query = ( self . query . filter ( Commodity . mnemonic . in_ ( symbols ) ) ) . order_by ( Commodity . namespace , Commodity . mnemonic ) return query . all ( ) | loads stocks by symbol | 71 | 4 |
248,802 | def get_aggregate ( self , security : Commodity ) -> SecurityAggregate : assert security is not None assert isinstance ( security , Commodity ) return SecurityAggregate ( self . book , security ) | Returns the aggregate for the entity | 45 | 6 |
248,803 | def get_aggregate_for_symbol ( self , symbol : str ) -> SecurityAggregate : security = self . get_by_symbol ( symbol ) if not security : raise ValueError ( f"Security not found in GC book: {symbol}!" ) return self . get_aggregate ( security ) | Returns the aggregate for the security found by full symbol | 68 | 10 |
248,804 | def query ( self ) : query = ( self . book . session . query ( Commodity ) . filter ( Commodity . namespace != "CURRENCY" , Commodity . namespace != "template" ) ) return query | Returns the base query which filters out data for all queries . | 49 | 12 |
248,805 | def book ( self ) -> Book : if not self . __book : # Create/open the book. book_uri = self . settings . database_path self . __book = Database ( book_uri ) . open_book ( for_writing = self . __for_writing ) return self . __book | GnuCash Book . Opens the book or creates an database based on settings . | 65 | 17 |
248,806 | def accounts ( self ) -> AccountsAggregate : if not self . __accounts_aggregate : self . __accounts_aggregate = AccountsAggregate ( self . book ) return self . __accounts_aggregate | Returns the Accounts aggregate | 47 | 4 |
248,807 | def currencies ( self ) -> CurrenciesAggregate : if not self . __currencies_aggregate : self . __currencies_aggregate = CurrenciesAggregate ( self . book ) return self . __currencies_aggregate | Returns the Currencies aggregate | 49 | 5 |
248,808 | def securities ( self ) : if not self . __securities_aggregate : self . __securities_aggregate = SecuritiesAggregate ( self . book ) return self . __securities_aggregate | Returns securities aggregate | 43 | 3 |
248,809 | def get_currency_symbols ( self ) -> List [ str ] : result = [ ] currencies = self . currencies . get_book_currencies ( ) for cur in currencies : result . append ( cur . mnemonic ) return result | Returns the used currencies symbols as an array | 52 | 8 |
248,810 | def load_jinja_template ( file_name ) : original_script_path = sys . argv [ 0 ] #script_path = os.path.dirname(os.path.realpath(__file__)) script_dir = os . path . dirname ( original_script_path ) # file_path = os.path.join(script_path, file_name) # with open(file_path, 'r') as template_file: # return template_file.read() from jinja2 import Environment , FileSystemLoader env = Environment ( loader = FileSystemLoader ( script_dir ) ) template = env . get_template ( file_name ) return template | Loads the jinja2 HTML template from the given file . Assumes that the file is in the same directory as the script . | 149 | 28 |
248,811 | def get_days_in_month ( year : int , month : int ) -> int : month_range = calendar . monthrange ( year , month ) return month_range [ 1 ] | Returns number of days in the given month . 1 - based numbers as arguments . i . e . November = 11 | 40 | 23 |
248,812 | def get_from_gnucash26_date ( date_str : str ) -> date : date_format = "%Y%m%d" result = datetime . strptime ( date_str , date_format ) . date ( ) return result | Creates a datetime from GnuCash 2 . 6 date string | 55 | 14 |
248,813 | def parse_period ( period : str ) : period = period . split ( " - " ) date_from = Datum ( ) if len ( period [ 0 ] ) == 10 : date_from . from_iso_date_string ( period [ 0 ] ) else : date_from . from_iso_long_date ( period [ 0 ] ) date_from . start_of_day ( ) date_to = Datum ( ) if len ( period [ 1 ] ) == 10 : date_to . from_iso_date_string ( period [ 1 ] ) else : date_to . from_iso_long_date ( period [ 1 ] ) date_to . end_of_day ( ) return date_from . value , date_to . value | parses period from date range picker . The received values are full ISO date | 164 | 17 |
248,814 | def get_period ( date_from : date , date_to : date ) -> str : assert isinstance ( date_from , date ) assert isinstance ( date_to , date ) str_from : str = date_from . isoformat ( ) str_to : str = date_to . isoformat ( ) return str_from + " - " + str_to | Returns the period string from the given dates | 80 | 8 |
248,815 | def load_json_file_contents ( path : str ) -> str : assert isinstance ( path , str ) content = None file_path = os . path . abspath ( path ) content = fileutils . read_text_from_file ( file_path ) json_object = json . loads ( content ) content = json . dumps ( json_object , sort_keys = True , indent = 4 ) return content | Loads contents from a json file | 90 | 7 |
248,816 | def validate_json ( data : str ) : result = None try : result = json . loads ( data ) except ValueError as error : log ( ERROR , "invalid json: %s" , error ) return result | Validate JSON by parsing string data . Returns the json dict . | 46 | 13 |
248,817 | def get_sql ( query ) : sql = str ( query . statement . compile ( dialect = sqlite . dialect ( ) , compile_kwargs = { "literal_binds" : True } ) ) return sql | Returns the sql query | 47 | 4 |
248,818 | def save_to_temp ( content , file_name = None ) : #output = "results.html" temp_dir = tempfile . gettempdir ( ) #tempfile.TemporaryDirectory() #tempfile.NamedTemporaryFile(mode='w+t') as f: out_file = os . path . join ( temp_dir , file_name ) #if os.path.exists(output) and os.path.isfile(output): file = open ( out_file , 'w' ) file . write ( content ) file . close ( ) #print("results saved in results.html file.") #return output #output = str(pathlib.Path(f.name)) return out_file | Save the contents into a temp file . | 157 | 8 |
248,819 | def read_book_uri_from_console ( ) : db_path : str = input ( "Enter book_url or leave blank for the default settings value: " ) if db_path : # sqlite if db_path . startswith ( "sqlite://" ) : db_path_uri = db_path else : # TODO: check if file exists. db_path_uri = "file:///" + db_path else : cfg = settings . Settings ( ) db_path_uri = cfg . database_uri return db_path_uri | Prompts the user to enter book url in console | 123 | 11 |
248,820 | def run_report_from_console ( output_file_name , callback ) : print ( "The report uses a read-only access to the book." ) print ( "Now enter the data or ^Z to continue:" ) #report_method = kwargs["report_method"] result = callback ( ) #output_file_name = kwargs["output_file_name"] output = save_to_temp ( result , output_file_name ) webbrowser . open ( output ) | Runs the report from the command line . Receives the book url from the console . | 106 | 18 |
248,821 | def get_dividend_sum_for_symbol ( book : Book , symbol : str ) : svc = SecuritiesAggregate ( book ) security = svc . get_by_symbol ( symbol ) sec_svc = SecurityAggregate ( book , security ) accounts = sec_svc . get_income_accounts ( ) total = Decimal ( 0 ) for account in accounts : # get all dividends. income = get_dividend_sum ( book , account ) total += income return total | Calculates all income for a symbol | 110 | 8 |
248,822 | def import_file ( filename ) : #file_path = os.path.relpath(filename) file_path = os . path . abspath ( filename ) log ( DEBUG , "Loading prices from %s" , file_path ) prices = __read_prices_from_file ( file_path ) with BookAggregate ( for_writing = True ) as svc : svc . prices . import_prices ( prices ) print ( "Saving book..." ) svc . book . save ( ) | Imports the commodity prices from the given . csv file . | 110 | 13 |
248,823 | def generate_report ( book_url ) : # commodity: CommodityOption( # section="Commodity", # sort_tag="a", # documentation_string="This is a stock", # default_value="VTIP"), # commodity_list: CommodityListOption( # section="Commodity", # sort_tag="a", # documentation_string="This is a stock", # default_value="VTIP") #): # Report variables shares_no = None avg_price = None stock_template = templates . load_jinja_template ( "stock_template.html" ) stock_rows = "" with piecash . open_book ( book_url , readonly = True , open_if_lock = True ) as book : # get all commodities that are not currencies. all_stocks = portfoliovalue . get_all_stocks ( book ) for stock in all_stocks : for_date = datetime . today ( ) . date model = portfoliovalue . get_stock_model_from ( book , stock , for_date ) stock_rows += stock_template . render ( model ) # Load HTML template file. template = templates . load_jinja_template ( "template.html" ) # Render the full report. #return template.format(**locals()) result = template . render ( * * locals ( ) ) return result | Generates an HTML report content . | 297 | 7 |
248,824 | def main ( symbol : str ) : print ( "Displaying the balance for" , symbol ) with BookAggregate ( ) as svc : security = svc . book . get ( Commodity , mnemonic = symbol ) #security.transactions, security.prices sec_svc = SecurityAggregate ( svc . book , security ) # Display number of shares shares_no = sec_svc . get_quantity ( ) print ( "Quantity:" , shares_no ) # Calculate average price. avg_price = sec_svc . get_avg_price ( ) print ( "Average price:" , avg_price ) | Displays the balance for the security symbol . | 139 | 9 |
248,825 | def generate_report ( book_url ) : with piecash . open_book ( book_url , readonly = True , open_if_lock = True ) as book : accounts = [ acc . fullname for acc in book . accounts ] return f"""<html> <body> Hello world from python !<br> Book : {book_url}<br> List of accounts : {accounts} </body> </html>""" | Generates the report HTML . | 94 | 6 |
248,826 | def get_project_files ( ) : if is_git_project ( ) : return get_git_project_files ( ) project_files = [ ] for top , subdirs , files in os . walk ( '.' ) : for subdir in subdirs : if subdir . startswith ( '.' ) : subdirs . remove ( subdir ) for f in files : if f . startswith ( '.' ) : continue project_files . append ( os . path . join ( top , f ) ) return project_files | Retrieve a list of project files ignoring hidden files . | 118 | 11 |
248,827 | def print_success_message ( message ) : try : import colorama print ( colorama . Fore . GREEN + message + colorama . Fore . RESET ) except ImportError : print ( message ) | Print a message indicating success in green color to STDOUT . | 42 | 12 |
248,828 | def print_failure_message ( message ) : try : import colorama print ( colorama . Fore . RED + message + colorama . Fore . RESET , file = sys . stderr ) except ImportError : print ( message , file = sys . stderr ) | Print a message indicating failure in red color to STDERR . | 59 | 12 |
248,829 | def main ( ) : importer = ExchangeRatesImporter ( ) print ( "####################################" ) latest_rates_json = importer . get_latest_rates ( ) # translate into an array of PriceModels # TODO mapper = currencyrates.FixerioModelMapper() mapper = None rates = mapper . map_to_model ( latest_rates_json ) print ( "####################################" ) print ( "importing rates into gnucash..." ) # For writing, use True below. with BookAggregate ( for_writing = False ) as svc : svc . currencies . import_fx_rates ( rates ) print ( "####################################" ) print ( "displaying rates from gnucash..." ) importer . display_gnucash_rates ( ) | Default entry point | 170 | 3 |
248,830 | def generate_asset_allocation_report ( book_url ) : model = load_asset_allocation_model ( book_url ) # load display template template = templates . load_jinja_template ( "report_asset_allocation.html" ) # render template result = template . render ( model = model ) # **locals() return result | The otput is generated here . Separated from the generate_report function to allow executing from the command line . | 79 | 24 |
248,831 | def parse_value ( self , value_string : str ) : self . value = Decimal ( value_string ) return self . value | Parses the amount string . | 29 | 7 |
248,832 | def parse ( self , csv_row : str ) : self . date = self . parse_euro_date ( csv_row [ 2 ] ) self . symbol = csv_row [ 0 ] self . value = self . parse_value ( csv_row [ 1 ] ) return self | Parses the . csv row into own values | 64 | 11 |
248,833 | def load_cash_balances_with_children ( self , root_account_fullname : str ) : assert isinstance ( root_account_fullname , str ) svc = AccountsAggregate ( self . book ) root_account = svc . get_by_fullname ( root_account_fullname ) if not root_account : raise ValueError ( "Account not found" , root_account_fullname ) accounts = self . __get_all_child_accounts_as_array ( root_account ) # read cash balances model = { } for account in accounts : if account . commodity . namespace != "CURRENCY" or account . placeholder : continue # separate per currency currency_symbol = account . commodity . mnemonic if not currency_symbol in model : # Add the currency branch. currency_record = { "name" : currency_symbol , "total" : 0 , "rows" : [ ] } # Append to the root. model [ currency_symbol ] = currency_record else : currency_record = model [ currency_symbol ] #acct_svc = AccountAggregate(self.book, account) balance = account . get_balance ( ) row = { "name" : account . name , "fullname" : account . fullname , "currency" : currency_symbol , "balance" : balance } currency_record [ "rows" ] . append ( row ) # add to total total = Decimal ( currency_record [ "total" ] ) total += balance currency_record [ "total" ] = total return model | loads data for cash balances | 342 | 5 |
248,834 | def get_balance ( self ) : on_date = Datum ( ) on_date . today ( ) return self . get_balance_on ( on_date . value ) | Current account balance | 38 | 3 |
248,835 | def get_splits_query ( self ) : query = ( self . book . session . query ( Split ) . filter ( Split . account == self . account ) ) return query | Returns all the splits in the account | 38 | 7 |
248,836 | def get_transactions ( self , date_from : datetime , date_to : datetime ) -> List [ Transaction ] : assert isinstance ( date_from , datetime ) assert isinstance ( date_to , datetime ) # fix up the parameters as we need datetime dt_from = Datum ( ) dt_from . from_datetime ( date_from ) dt_from . start_of_day ( ) dt_to = Datum ( ) dt_to . from_datetime ( date_to ) dt_to . end_of_day ( ) query = ( self . book . session . query ( Transaction ) . join ( Split ) . filter ( Split . account_guid == self . account . guid ) . filter ( Transaction . post_date >= dt_from . date , Transaction . post_date <= dt_to . date ) . order_by ( Transaction . post_date ) ) return query . all ( ) | Returns account transactions | 211 | 3 |
248,837 | def __get_all_child_accounts_as_array ( self , account : Account ) -> List [ Account ] : result = [ ] # ignore placeholders ? - what if a brokerage account has cash/stocks division? # if not account.placeholder: # continue result . append ( account ) for child in account . children : sub_accounts = self . __get_all_child_accounts_as_array ( child ) result += sub_accounts return result | Returns the whole tree of child accounts in a list | 102 | 10 |
248,838 | def find_by_name ( self , term : str , include_placeholders : bool = False ) -> List [ Account ] : query = ( self . query . filter ( Account . name . like ( '%' + term + '%' ) ) . order_by ( Account . name ) ) # Exclude placeholder accounts? if not include_placeholders : query = query . filter ( Account . placeholder == 0 ) # print(generic.get_sql(query)) return query . all ( ) | Search for account by part of the name | 106 | 8 |
248,839 | def get_aggregate_by_id ( self , account_id : str ) -> AccountAggregate : account = self . get_by_id ( account_id ) return self . get_account_aggregate ( account ) | Returns the aggregate for the given id | 49 | 7 |
248,840 | def get_by_fullname ( self , fullname : str ) -> Account : # get all accounts and iterate, comparing the fullname. :S query = ( self . book . session . query ( Account ) ) # generic.get_sql() # print(sql) all_accounts = query . all ( ) for account in all_accounts : if account . fullname == fullname : return account # else return None | Loads account by full name | 92 | 6 |
248,841 | def get_account_id_by_fullname ( self , fullname : str ) -> str : account = self . get_by_fullname ( fullname ) return account . guid | Locates the account by fullname | 40 | 7 |
248,842 | def get_all_children ( self , fullname : str ) -> List [ Account ] : # find the account by fullname root_acct = self . get_by_fullname ( fullname ) if not root_acct : raise NameError ( "Account not found in book!" ) acct_agg = self . get_account_aggregate ( root_acct ) result = acct_agg . get_all_child_accounts_as_array ( ) # for child in root_acct.children: # log(DEBUG, "found child %s", child.fullname) return result | Returns the whole child account tree for the account with the given full name | 132 | 14 |
248,843 | def get_all ( self ) -> List [ Account ] : return [ account for account in self . book . accounts if account . parent . name != "Template Root" ] | Returns all book accounts as a list excluding templates . | 36 | 10 |
248,844 | def get_favourite_accounts ( self ) -> List [ Account ] : from gnucash_portfolio . lib . settings import Settings settings = Settings ( ) favourite_accts = settings . favourite_accounts accounts = self . get_list ( favourite_accts ) return accounts | Provides a list of favourite accounts | 64 | 7 |
248,845 | def get_favourite_account_aggregates ( self ) -> List [ AccountAggregate ] : accounts = self . get_favourite_accounts ( ) aggregates = [ ] for account in accounts : aggregate = self . get_account_aggregate ( account ) aggregates . append ( aggregate ) return aggregates | Returns the list of aggregates for favourite accounts | 70 | 9 |
248,846 | def get_by_id ( self , acct_id ) -> Account : return self . book . get ( Account , guid = acct_id ) | Loads an account entity | 33 | 5 |
248,847 | def get_by_name ( self , name : str ) -> List [ Account ] : # return self.query.filter(Account.name == name).all() return self . get_by_name_from ( self . book . root , name ) | Searches accounts by name | 54 | 6 |
248,848 | def get_by_name_from ( self , root : Account , name : str ) -> List [ Account ] : result = [ ] if root . name == name : result . append ( root ) for child in root . children : child_results = self . get_by_name_from ( child , name ) result += child_results return result | Searches child accounts by name starting from the given account | 74 | 12 |
248,849 | def get_list ( self , ids : List [ str ] ) -> List [ Account ] : query = ( self . query . filter ( Account . guid . in_ ( ids ) ) ) return query . all ( ) | Loads accounts by the ids passed as an argument | 48 | 11 |
248,850 | def query ( self ) : query = ( self . book . session . query ( Account ) . join ( Commodity ) . filter ( Commodity . namespace != "template" ) . filter ( Account . type != AccountType . root . value ) ) return query | Main accounts query | 56 | 3 |
248,851 | def search ( self , name : str = None , acc_type : str = None ) : query = self . query if name is not None : query = query . filter ( Account . name == name ) if acc_type is not None : # account type is capitalized acc_type = acc_type . upper ( ) query = query . filter ( Account . type == acc_type ) return query . all ( ) | Search accounts by passing parameters . name = exact name name_part = part of name parent_id = id of the parent account type = account type | 88 | 30 |
248,852 | def get_price_as_of ( self , stock : Commodity , on_date : datetime ) : # return self.get_price_as_of_query(stock, on_date).first() prices = PriceDbApplication ( ) prices . get_prices_on ( on_date . date ( ) . isoformat ( ) , stock . namespace , stock . mnemonic ) | Gets the latest price on or before the given date . | 86 | 12 |
248,853 | def import_price ( self , price : PriceModel ) : # Handle yahoo-style symbols with extension. symbol = price . symbol if "." in symbol : symbol = price . symbol . split ( "." ) [ 0 ] stock = SecuritiesAggregate ( self . book ) . get_by_symbol ( symbol ) # get_aggregate_for_symbol if stock is None : logging . warning ( "security %s not found in book." , price . symbol ) return False # check if there is already a price for the date existing_prices = stock . prices . filter ( Price . date == price . datetime . date ( ) ) . all ( ) if not existing_prices : # Create new price for the commodity (symbol). self . __create_price_for ( stock , price ) else : logging . warning ( "price already exists for %s on %s" , stock . mnemonic , price . datetime . strftime ( "%Y-%m-%d" ) ) existing_price = existing_prices [ 0 ] # update price existing_price . value = price . value return True | Import individual price | 241 | 3 |
248,854 | def __create_price_for ( self , commodity : Commodity , price : PriceModel ) : logging . info ( "Adding a new price for %s, %s, %s" , commodity . mnemonic , price . datetime . strftime ( "%Y-%m-%d" ) , price . value ) # safety check. Compare currencies. sec_svc = SecurityAggregate ( self . book , commodity ) currency = sec_svc . get_currency ( ) if currency != price . currency : raise ValueError ( "Requested currency does not match the currency previously used" , currency , price . currency ) # Description of the source field values: # https://www.gnucash.org/docs/v2.6/C/gnucash-help/tool-price.html new_price = Price ( commodity , currency , price . datetime . date ( ) , price . value , source = "Finance::Quote" ) commodity . prices . append ( new_price ) | Creates a new Price entry in the book for the given commodity | 216 | 13 |
248,855 | def get_splits_query ( self ) : query = ( self . book . session . query ( Split ) # .join(Transaction) . filter ( Split . transaction_guid == self . transaction . guid ) ) return query | Returns the query for related splits | 49 | 6 |
248,856 | def generate_report ( book_url , fund_ids : StringOption ( section = "Funds" , sort_tag = "c" , documentation_string = "Comma-separated list of fund ids." , default_value = "8123,8146,8148,8147" ) ) : return render_report ( book_url , fund_ids ) | Generates the report output | 81 | 5 |
248,857 | def searchAccount ( searchTerm , book ) : print ( "Search results:\n" ) found = False # search for account in book . accounts : # print(account.fullname) # name if searchTerm . lower ( ) in account . fullname . lower ( ) : print ( account . fullname ) found = True if not found : print ( "Search term not found in account names." ) | Searches through account names | 84 | 6 |
248,858 | def display_db_info ( self ) : with self . open_book ( ) as book : default_currency = book . default_currency print ( "Default currency is " , default_currency . mnemonic ) | Displays some basic info about the GnuCash book | 46 | 11 |
248,859 | def open_book ( self , for_writing = False ) -> piecash . Book : filename = None # check if the file path is already a URL. file_url = urllib . parse . urlparse ( self . filename ) if file_url . scheme == "file" or file_url . scheme == "sqlite" : filename = file_url . path [ 1 : ] else : filename = self . filename if not os . path . isfile ( filename ) : log ( WARN , "Database %s requested but not found. Creating an in-memory book." , filename ) return self . create_book ( ) access_type = "read/write" if for_writing else "readonly" log ( INFO , "Using %s in %s mode." , filename , access_type ) # file_path = path.relpath(self.filename) file_path = path . abspath ( filename ) if not for_writing : book = piecash . open_book ( file_path , open_if_lock = True ) else : book = piecash . open_book ( file_path , open_if_lock = True , readonly = False ) # book = create_book() return book | Opens the database . Call this using with . If database file is not found an in - memory database will be created . | 260 | 25 |
248,860 | def read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content | Reads text file contents | 37 | 5 |
248,861 | def save_text_to_file ( content : str , path : str ) : with open ( path , mode = 'w' ) as text_file : text_file . write ( content ) | Saves text to file | 42 | 5 |
248,862 | def get_amount_in_base_currency ( self , currency : str , amount : Decimal ) -> Decimal : assert isinstance ( amount , Decimal ) # If this is already the base currency, do nothing. if currency == self . get_default_currency ( ) . mnemonic : return amount agg = self . get_currency_aggregate_by_symbol ( currency ) if not agg : raise ValueError ( f"Currency not found: {currency}!" ) # TODO use pricedb for the price. rate_to_base = agg . get_latest_price ( ) if not rate_to_base : raise ValueError ( f"Latest price not found for {currency}!" ) assert isinstance ( rate_to_base . value , Decimal ) result = amount * rate_to_base . value return result | Calculates the amount in base currency | 181 | 8 |
248,863 | def get_default_currency ( self ) -> Commodity : result = None if self . default_currency : result = self . default_currency else : def_currency = self . __get_default_currency ( ) self . default_currency = def_currency result = def_currency return result | returns the book default currency | 63 | 6 |
248,864 | def get_book_currencies ( self ) -> List [ Commodity ] : query = ( self . currencies_query . order_by ( Commodity . mnemonic ) ) return query . all ( ) | Returns currencies used in the book | 46 | 6 |
248,865 | def get_currency_aggregate_by_symbol ( self , symbol : str ) -> CurrencyAggregate : currency = self . get_by_symbol ( symbol ) result = self . get_currency_aggregate ( currency ) return result | Creates currency aggregate for the given currency symbol | 52 | 9 |
248,866 | def get_by_symbol ( self , symbol : str ) -> Commodity : assert isinstance ( symbol , str ) query = ( self . currencies_query . filter ( Commodity . mnemonic == symbol ) ) return query . one ( ) | Loads currency by symbol | 55 | 5 |
248,867 | def import_fx_rates ( self , rates : List [ PriceModel ] ) : have_new_rates = False base_currency = self . get_default_currency ( ) for rate in rates : assert isinstance ( rate , PriceModel ) currency = self . get_by_symbol ( rate . symbol ) amount = rate . value # Do not import duplicate prices. # todo: if the price differs, update it! # exists_query = exists(rates_query) has_rate = currency . prices . filter ( Price . date == rate . datetime . date ( ) ) . first ( ) # has_rate = ( # self.book.session.query(Price) # .filter(Price.date == rate.date.date()) # .filter(Price.currency == currency) # ) if not has_rate : log ( INFO , "Creating entry for %s, %s, %s, %s" , base_currency . mnemonic , currency . mnemonic , rate . datetime . date ( ) , amount ) # Save the price in the exchange currency, not the default. # Invert the rate in that case. inverted_rate = 1 / amount inverted_rate = inverted_rate . quantize ( Decimal ( '.00000000' ) ) price = Price ( commodity = currency , currency = base_currency , date = rate . datetime . date ( ) , value = str ( inverted_rate ) ) have_new_rates = True # Save the book after the prices have been created. if have_new_rates : log ( INFO , "Saving new prices..." ) self . book . flush ( ) self . book . save ( ) else : log ( INFO , "No prices imported." ) | Imports the given prices into database . Write operation! | 368 | 11 |
248,868 | def __get_default_currency ( self ) : # If we are on Windows, read from registry. if sys . platform == "win32" : # read from registry def_curr = self . book [ "default-currency" ] = self . __get_default_currency_windows ( ) else : # return the currency from locale. # todo: Read the preferences on other operating systems. def_curr = self . book [ "default-currency" ] = self . __get_locale_currency ( ) return def_curr | Read the default currency from GnuCash preferences | 117 | 9 |
248,869 | def __get_registry_key ( self , key ) : import winreg root = winreg . OpenKey ( winreg . HKEY_CURRENT_USER , r'SOFTWARE\GSettings\org\gnucash\general' , 0 , winreg . KEY_READ ) [ pathname , regtype ] = ( winreg . QueryValueEx ( root , key ) ) winreg . CloseKey ( root ) return pathname | Read currency from windows registry | 94 | 5 |
248,870 | def get_for_accounts ( self , accounts : List [ Account ] ) : account_ids = [ acc . guid for acc in accounts ] query = ( self . query . filter ( Split . account_guid . in_ ( account_ids ) ) ) splits = query . all ( ) return splits | Get all splits for the given accounts | 65 | 7 |
248,871 | def __get_model_for_portfolio_value ( input_model : PortfolioValueInputModel ) -> PortfolioValueViewModel : result = PortfolioValueViewModel ( ) result . filter = input_model ref_datum = Datum ( ) ref_datum . from_datetime ( input_model . as_of_date ) ref_date = ref_datum . end_of_day ( ) result . stock_rows = [ ] with BookAggregate ( ) as svc : book = svc . book stocks_svc = svc . securities if input_model . stock : symbols = input_model . stock . split ( "," ) stocks = stocks_svc . get_stocks ( symbols ) else : stocks = stocks_svc . get_all ( ) for stock in stocks : row : StockViewModel = portfoliovalue . get_stock_model_from ( book , stock , as_of_date = ref_date ) if row and row . balance > 0 : result . stock_rows . append ( row ) return result | loads the data for portfolio value | 231 | 6 |
248,872 | def __load_settings ( self ) : #file_path = path.relpath(settings_file_path) #file_path = path.abspath(settings_file_path) file_path = self . file_path try : self . data = json . load ( open ( file_path ) ) except FileNotFoundError : print ( "Could not load" , file_path ) | Load settings from . json file | 86 | 6 |
248,873 | def file_exists ( self ) -> bool : cfg_path = self . file_path assert cfg_path return path . isfile ( cfg_path ) | Check if the settings file exists or not | 37 | 8 |
248,874 | def save ( self ) : content = self . dumps ( ) fileutils . save_text_to_file ( content , self . file_path ) | Saves the settings contents | 32 | 5 |
248,875 | def database_path ( self ) : filename = self . database_filename db_path = ":memory:" if filename == ":memory:" else ( path . abspath ( path . join ( __file__ , "../.." , ".." , "data" , filename ) ) ) return db_path | Full database path . Includes the default location + the database filename . | 66 | 13 |
248,876 | def file_path ( self ) -> str : user_dir = self . __get_user_path ( ) file_path = path . abspath ( path . join ( user_dir , self . FILENAME ) ) return file_path | Settings file absolute path | 52 | 4 |
248,877 | def dumps ( self ) -> str : return json . dumps ( self . data , sort_keys = True , indent = 4 ) | Dumps the json content as a string | 27 | 8 |
248,878 | def __copy_template ( self ) : import shutil template_filename = "settings.json.template" template_path = path . abspath ( path . join ( __file__ , ".." , ".." , "config" , template_filename ) ) settings_path = self . file_path shutil . copyfile ( template_path , settings_path ) self . __ensure_file_exists ( ) | Copy the settings template into the user s directory | 92 | 9 |
248,879 | def is_not_empty ( self , value , strict = False ) : value = stringify ( value ) if value is not None : return self . shout ( 'Value %r is empty' , strict , value ) | if value is not empty | 46 | 5 |
248,880 | def is_numeric ( self , value , strict = False ) : value = stringify ( value ) if value is not None : if value . isnumeric ( ) : return self . shout ( 'value %r is not numeric' , strict , value ) | if value is numeric | 54 | 4 |
248,881 | def is_integer ( self , value , strict = False ) : if value is not None : if isinstance ( value , numbers . Number ) : return value = stringify ( value ) if value is not None and value . isnumeric ( ) : return self . shout ( 'value %r is not an integer' , strict , value ) | if value is an integer | 71 | 5 |
248,882 | def match_date ( self , value , strict = False ) : value = stringify ( value ) try : parse ( value ) except Exception : self . shout ( 'Value %r is not a valid date' , strict , value ) | if value is a date | 49 | 5 |
248,883 | def match_regexp ( self , value , q , strict = False ) : value = stringify ( value ) mr = re . compile ( q ) if value is not None : if mr . match ( value ) : return self . shout ( '%r not matching the regexp %r' , strict , value , q ) | if value matches a regexp q | 72 | 7 |
248,884 | def has_length ( self , value , q , strict = False ) : value = stringify ( value ) if value is not None : if len ( value ) == q : return self . shout ( 'Value %r not matching length %r' , strict , value , q ) | if value has a length of q | 59 | 7 |
248,885 | def must_contain ( self , value , q , strict = False ) : if value is not None : if value . find ( q ) != - 1 : return self . shout ( 'Value %r does not contain %r' , strict , value , q ) | if value must contain q | 56 | 5 |
248,886 | def extract ( context , data ) : with context . http . rehash ( data ) as result : file_path = result . file_path content_type = result . content_type extract_dir = random_filename ( context . work_path ) if content_type in ZIP_MIME_TYPES : extracted_files = extract_zip ( file_path , extract_dir ) elif content_type in TAR_MIME_TYPES : extracted_files = extract_tar ( file_path , extract_dir , context ) elif content_type in SEVENZIP_MIME_TYPES : extracted_files = extract_7zip ( file_path , extract_dir , context ) else : context . log . warning ( "Unsupported archive content type: %s" , content_type ) return extracted_content_hashes = { } for path in extracted_files : relative_path = os . path . relpath ( path , extract_dir ) content_hash = context . store_file ( path ) extracted_content_hashes [ relative_path ] = content_hash data [ 'content_hash' ] = content_hash data [ 'file_name' ] = relative_path context . emit ( data = data . copy ( ) ) | Extract a compressed file | 274 | 5 |
248,887 | def size ( cls , crawler ) : key = make_key ( 'queue_pending' , crawler ) return unpack_int ( conn . get ( key ) ) | Total operations pending for this crawler | 39 | 7 |
248,888 | def read_word ( image , whitelist = None , chars = None , spaces = False ) : from tesserocr import PyTessBaseAPI api = PyTessBaseAPI ( ) api . SetPageSegMode ( 8 ) if whitelist is not None : api . SetVariable ( "tessedit_char_whitelist" , whitelist ) api . SetImage ( image ) api . Recognize ( ) guess = api . GetUTF8Text ( ) if not spaces : guess = '' . join ( [ c for c in guess if c != " " ] ) guess = guess . strip ( ) if chars is not None and len ( guess ) != chars : return guess , None return guess , api . MeanTextConf ( ) | OCR a single word from an image . Useful for captchas . Image should be pre - processed to remove noise etc . | 157 | 26 |
248,889 | def read_char ( image , whitelist = None ) : from tesserocr import PyTessBaseAPI api = PyTessBaseAPI ( ) api . SetPageSegMode ( 10 ) if whitelist is not None : api . SetVariable ( "tessedit_char_whitelist" , whitelist ) api . SetImage ( image ) api . Recognize ( ) return api . GetUTF8Text ( ) . strip ( ) | OCR a single character from an image . Useful for captchas . | 95 | 15 |
248,890 | def get ( self , name , default = None ) : value = self . params . get ( name , default ) if isinstance ( value , str ) : value = os . path . expandvars ( value ) return value | Get a configuration value and expand environment variables . | 47 | 9 |
248,891 | def emit ( self , rule = 'pass' , stage = None , data = { } , delay = None , optional = False ) : if stage is None : stage = self . stage . handlers . get ( rule ) if optional and stage is None : return if stage is None or stage not in self . crawler . stages : self . log . info ( "No next stage: %s (%s)" % ( stage , rule ) ) return state = self . dump_state ( ) delay = delay or self . crawler . delay Queue . queue ( stage , state , data , delay ) | Invoke the next stage either based on a handling rule or by calling the pass rule by default . | 125 | 20 |
248,892 | def recurse ( self , data = { } , delay = None ) : return self . emit ( stage = self . stage . name , data = data , delay = delay ) | Have a stage invoke itself with a modified set of arguments . | 37 | 12 |
248,893 | def execute ( self , data ) : if Crawl . is_aborted ( self . crawler , self . run_id ) : return try : Crawl . operation_start ( self . crawler , self . stage , self . run_id ) self . log . info ( '[%s->%s(%s)]: %s' , self . crawler . name , self . stage . name , self . stage . method_name , self . run_id ) return self . stage . method ( self , data ) except Exception as exc : self . emit_exception ( exc ) finally : Crawl . operation_end ( self . crawler , self . run_id ) shutil . rmtree ( self . work_path ) | Execute the crawler and create a database record of having done so . | 160 | 15 |
248,894 | def skip_incremental ( self , * criteria ) : if not self . incremental : return False # this is pure convenience, and will probably backfire at some point. key = make_key ( * criteria ) if key is None : return False if self . check_tag ( key ) : return True self . set_tag ( key , None ) return False | Perform an incremental check on a set of criteria . | 75 | 11 |
248,895 | def store_data ( self , data , encoding = 'utf-8' ) : path = random_filename ( self . work_path ) try : with open ( path , 'wb' ) as fh : if isinstance ( data , str ) : data = data . encode ( encoding ) if data is not None : fh . write ( data ) return self . store_file ( path ) finally : try : os . unlink ( path ) except OSError : pass | Put the given content into a file possibly encoding it as UTF - 8 in the process . | 102 | 18 |
248,896 | def check_due ( self ) : if self . disabled : return False if self . is_running : return False if self . delta is None : return False last_run = self . last_run if last_run is None : return True now = datetime . utcnow ( ) if now > last_run + self . delta : return True return False | Check if the last execution of this crawler is older than the scheduled interval . | 76 | 16 |
248,897 | def flush ( self ) : Queue . flush ( self ) Event . delete ( self ) Crawl . flush ( self ) | Delete all run - time data generated by this crawler . | 26 | 12 |
248,898 | def run ( self , incremental = None , run_id = None ) : state = { 'crawler' : self . name , 'run_id' : run_id , 'incremental' : settings . INCREMENTAL } if incremental is not None : state [ 'incremental' ] = incremental # Cancel previous runs: self . cancel ( ) # Flush out previous events: Event . delete ( self ) Queue . queue ( self . init_stage , state , { } ) | Queue the execution of a particular crawler . | 104 | 9 |
248,899 | def fetch ( context , data ) : url = data . get ( 'url' ) attempt = data . pop ( 'retry_attempt' , 1 ) try : result = context . http . get ( url , lazy = True ) rules = context . get ( 'rules' , { 'match_all' : { } } ) if not Rule . get_rule ( rules ) . apply ( result ) : context . log . info ( 'Fetch skip: %r' , result . url ) return if not result . ok : err = ( result . url , result . status_code ) context . emit_warning ( "Fetch fail [%s]: HTTP %s" % err ) if not context . params . get ( 'emit_errors' , False ) : return else : context . log . info ( "Fetched [%s]: %r" , result . status_code , result . url ) data . update ( result . serialize ( ) ) if url != result . url : tag = make_key ( context . run_id , url ) context . set_tag ( tag , None ) context . emit ( data = data ) except RequestException as ce : retries = int ( context . get ( 'retry' , 3 ) ) if retries >= attempt : context . log . warn ( "Retry: %s (error: %s)" , url , ce ) data [ 'retry_attempt' ] = attempt + 1 context . recurse ( data = data , delay = 2 ** attempt ) else : context . emit_warning ( "Fetch fail [%s]: %s" % ( url , ce ) ) | Do an HTTP GET on the url specified in the inbound data . | 353 | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.