repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
MisterY/asset-allocation
asset_allocation/model.py
AssetAllocationModel.calculate_set_values
def calculate_set_values(self): """ Calculate the expected totals based on set allocations """ for ac in self.asset_classes: ac.alloc_value = self.total_amount * ac.allocation / Decimal(100)
python
def calculate_set_values(self): """ Calculate the expected totals based on set allocations """ for ac in self.asset_classes: ac.alloc_value = self.total_amount * ac.allocation / Decimal(100)
Calculate the expected totals based on set allocations
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L229-L232
MisterY/asset-allocation
asset_allocation/model.py
AssetAllocationModel.calculate_current_allocation
def calculate_current_allocation(self): """ Calculates the current allocation % based on the value """ for ac in self.asset_classes: ac.curr_alloc = ac.curr_value * 100 / self.total_amount
python
def calculate_current_allocation(self): """ Calculates the current allocation % based on the value """ for ac in self.asset_classes: ac.curr_alloc = ac.curr_value * 100 / self.total_amount
Calculates the current allocation % based on the value
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L234-L237
MisterY/asset-allocation
asset_allocation/model.py
AssetAllocationModel.calculate_current_value
def calculate_current_value(self): """ Add all the stock values and assign to the asset classes """ # must be recursive total = Decimal(0) for ac in self.classes: self.__calculate_current_value(ac) total += ac.curr_value self.total_amount = total
python
def calculate_current_value(self): """ Add all the stock values and assign to the asset classes """ # must be recursive total = Decimal(0) for ac in self.classes: self.__calculate_current_value(ac) total += ac.curr_value self.total_amount = total
Add all the stock values and assign to the asset classes
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L239-L246
MisterY/asset-allocation
asset_allocation/model.py
AssetAllocationModel.__calculate_current_value
def __calculate_current_value(self, asset_class: AssetClass): """ Calculate totals for asset class by adding all the children values """ # Is this the final asset class, the one with stocks? if asset_class.stocks: # add all the stocks stocks_sum = Decimal(0) f...
python
def __calculate_current_value(self, asset_class: AssetClass): """ Calculate totals for asset class by adding all the children values """ # Is this the final asset class, the one with stocks? if asset_class.stocks: # add all the stocks stocks_sum = Decimal(0) f...
Calculate totals for asset class by adding all the children values
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L248-L264
MisterY/asset-allocation
asset_allocation/currency.py
CurrencyConverter.load_currency
def load_currency(self, mnemonic: str): """ load the latest rate for the given mnemonic; expressed in the base currency """ # , base_currency: str <= ignored for now. if self.rate and self.rate.currency == mnemonic: # Already loaded. return app = PriceDbApplicati...
python
def load_currency(self, mnemonic: str): """ load the latest rate for the given mnemonic; expressed in the base currency """ # , base_currency: str <= ignored for now. if self.rate and self.rate.currency == mnemonic: # Already loaded. return app = PriceDbApplicati...
load the latest rate for the given mnemonic; expressed in the base currency
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/currency.py#L12-L24
MisterY/asset-allocation
asset_allocation/cli.py
show
def show(format, full): """ Print current allocation to the console. """ # load asset allocation app = AppAggregate() app.logger = logger model = app.get_asset_allocation() if format == "ascii": formatter = AsciiFormatter() elif format == "html": formatter = HtmlFormatter ...
python
def show(format, full): """ Print current allocation to the console. """ # load asset allocation app = AppAggregate() app.logger = logger model = app.get_asset_allocation() if format == "ascii": formatter = AsciiFormatter() elif format == "html": formatter = HtmlFormatter ...
Print current allocation to the console.
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/cli.py#L30-L46
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.load_cash_balances
def load_cash_balances(self): """ Loads cash balances from GnuCash book and recalculates into the default currency """ from gnucash_portfolio.accounts import AccountsAggregate, AccountAggregate cfg = self.__get_config() cash_root_name = cfg.get(ConfigKeys.cash_root) # Load cash ...
python
def load_cash_balances(self): """ Loads cash balances from GnuCash book and recalculates into the default currency """ from gnucash_portfolio.accounts import AccountsAggregate, AccountAggregate cfg = self.__get_config() cash_root_name = cfg.get(ConfigKeys.cash_root) # Load cash ...
Loads cash balances from GnuCash book and recalculates into the default currency
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L29-L44
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.__store_cash_balances_per_currency
def __store_cash_balances_per_currency(self, cash_balances): """ Store balance per currency as Stock records under Cash class """ cash = self.model.get_cash_asset_class() for cur_symbol in cash_balances: item = CashBalance(cur_symbol) item.parent = cash ...
python
def __store_cash_balances_per_currency(self, cash_balances): """ Store balance per currency as Stock records under Cash class """ cash = self.model.get_cash_asset_class() for cur_symbol in cash_balances: item = CashBalance(cur_symbol) item.parent = cash ...
Store balance per currency as Stock records under Cash class
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L53-L67
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.load_tree_from_db
def load_tree_from_db(self) -> AssetAllocationModel: """ Reads the asset allocation data only, and constructs the AA tree """ self.model = AssetAllocationModel() # currency self.model.currency = self.__get_config().get(ConfigKeys.default_currency) # Asset Classes db = s...
python
def load_tree_from_db(self) -> AssetAllocationModel: """ Reads the asset allocation data only, and constructs the AA tree """ self.model = AssetAllocationModel() # currency self.model.currency = self.__get_config().get(ConfigKeys.default_currency) # Asset Classes db = s...
Reads the asset allocation data only, and constructs the AA tree
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L69-L95
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.load_stock_links
def load_stock_links(self): """ Read stock links into the model """ links = self.__get_session().query(dal.AssetClassStock).all() for entity in links: # log(DEBUG, f"adding {entity.symbol} to {entity.assetclassid}") # mapping stock: Stock = Stock(entity.symbol...
python
def load_stock_links(self): """ Read stock links into the model """ links = self.__get_session().query(dal.AssetClassStock).all() for entity in links: # log(DEBUG, f"adding {entity.symbol} to {entity.assetclassid}") # mapping stock: Stock = Stock(entity.symbol...
Read stock links into the model
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L97-L110
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.load_stock_quantity
def load_stock_quantity(self): """ Loads quantities for all stocks """ info = StocksInfo(self.config) for stock in self.model.stocks: stock.quantity = info.load_stock_quantity(stock.symbol) info.gc_book.close()
python
def load_stock_quantity(self): """ Loads quantities for all stocks """ info = StocksInfo(self.config) for stock in self.model.stocks: stock.quantity = info.load_stock_quantity(stock.symbol) info.gc_book.close()
Loads quantities for all stocks
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L112-L117
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.load_stock_prices
def load_stock_prices(self): """ Load latest prices for securities """ from pricedb import SecuritySymbol info = StocksInfo(self.config) for item in self.model.stocks: symbol = SecuritySymbol("", "") symbol.parse(item.symbol) price: PriceModel = info...
python
def load_stock_prices(self): """ Load latest prices for securities """ from pricedb import SecuritySymbol info = StocksInfo(self.config) for item in self.model.stocks: symbol = SecuritySymbol("", "") symbol.parse(item.symbol) price: PriceModel = info...
Load latest prices for securities
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L119-L138
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.recalculate_stock_values_into_base
def recalculate_stock_values_into_base(self): """ Loads the exchange rates and recalculates stock holding values into base currency """ from .currency import CurrencyConverter conv = CurrencyConverter() cash = self.model.get_cash_asset_class() for stock in self.model.s...
python
def recalculate_stock_values_into_base(self): """ Loads the exchange rates and recalculates stock holding values into base currency """ from .currency import CurrencyConverter conv = CurrencyConverter() cash = self.model.get_cash_asset_class() for stock in self.model.s...
Loads the exchange rates and recalculates stock holding values into base currency
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L140-L158
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.__load_child_classes
def __load_child_classes(self, ac: AssetClass): """ Loads child classes/stocks """ # load child classes for ac db = self.__get_session() entities = ( db.query(dal.AssetClass) .filter(dal.AssetClass.parentid == ac.id) .order_by(dal.AssetClass.sortorder)...
python
def __load_child_classes(self, ac: AssetClass): """ Loads child classes/stocks """ # load child classes for ac db = self.__get_session() entities = ( db.query(dal.AssetClass) .filter(dal.AssetClass.parentid == ac.id) .order_by(dal.AssetClass.sortorder)...
Loads child classes/stocks
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L161-L180
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.__map_entity
def __map_entity(self, entity: dal.AssetClass) -> AssetClass: """ maps the entity onto the model object """ mapper = self.__get_mapper() ac = mapper.map_entity(entity) return ac
python
def __map_entity(self, entity: dal.AssetClass) -> AssetClass: """ maps the entity onto the model object """ mapper = self.__get_mapper() ac = mapper.map_entity(entity) return ac
maps the entity onto the model object
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L182-L186
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.__get_session
def __get_session(self): """ Opens a db session """ db_path = self.__get_config().get(ConfigKeys.asset_allocation_database_path) self.session = dal.get_session(db_path) return self.session
python
def __get_session(self): """ Opens a db session """ db_path = self.__get_config().get(ConfigKeys.asset_allocation_database_path) self.session = dal.get_session(db_path) return self.session
Opens a db session
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L194-L198
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationLoader.__load_asset_class
def __load_asset_class(self, ac_id: int): """ Loads Asset Class entity """ # open database db = self.__get_session() entity = db.query(dal.AssetClass).filter(dal.AssetClass.id == ac_id).first() return entity
python
def __load_asset_class(self, ac_id: int): """ Loads Asset Class entity """ # open database db = self.__get_session() entity = db.query(dal.AssetClass).filter(dal.AssetClass.id == ac_id).first() return entity
Loads Asset Class entity
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L206-L211
MisterY/asset-allocation
asset_allocation/loader.py
AssetAllocationAggregate.__get_by_fullname
def __get_by_fullname(self, asset_class, fullname: str): """ Recursive function """ if asset_class.fullname == fullname: return asset_class if not hasattr(asset_class, "classes"): return None for child in asset_class.classes: found = self.__get_by_fu...
python
def __get_by_fullname(self, asset_class, fullname: str): """ Recursive function """ if asset_class.fullname == fullname: return asset_class if not hasattr(asset_class, "classes"): return None for child in asset_class.classes: found = self.__get_by_fu...
Recursive function
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/loader.py#L422-L435
MisterY/asset-allocation
asset_allocation/dal.py
get_session
def get_session(db_path: str): """ Creates and opens a database session """ # cfg = Config() # db_path = cfg.get(ConfigKeys.asset_allocation_database_path) # connection con_str = "sqlite:///" + db_path # Display all SQLite info with echo. engine = create_engine(con_str, echo=False) # c...
python
def get_session(db_path: str): """ Creates and opens a database session """ # cfg = Config() # db_path = cfg.get(ConfigKeys.asset_allocation_database_path) # connection con_str = "sqlite:///" + db_path # Display all SQLite info with echo. engine = create_engine(con_str, echo=False) # c...
Creates and opens a database session
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/dal.py#L53-L70
MisterY/asset-allocation
asset_allocation/assetclass_cli.py
add
def add(name): """ Add new Asset Class """ item = AssetClass() item.name = name app = AppAggregate() app.create_asset_class(item) print(f"Asset class {name} created.")
python
def add(name): """ Add new Asset Class """ item = AssetClass() item.name = name app = AppAggregate() app.create_asset_class(item) print(f"Asset class {name} created.")
Add new Asset Class
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L28-L35
MisterY/asset-allocation
asset_allocation/assetclass_cli.py
edit
def edit(id: int, parent: int, alloc: Decimal): """ Edit asset class """ saved = False # load app = AppAggregate() item = app.get(id) if not item: raise KeyError("Asset Class with id %s not found.", id) if parent: assert parent != id, "Parent can not be set to self." ...
python
def edit(id: int, parent: int, alloc: Decimal): """ Edit asset class """ saved = False # load app = AppAggregate() item = app.get(id) if not item: raise KeyError("Asset Class with id %s not found.", id) if parent: assert parent != id, "Parent can not be set to self." ...
Edit asset class
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L50-L79
MisterY/asset-allocation
asset_allocation/assetclass_cli.py
my_list
def my_list(): """ Lists all asset classes """ session = AppAggregate().open_session() classes = session.query(AssetClass).all() for item in classes: print(item)
python
def my_list(): """ Lists all asset classes """ session = AppAggregate().open_session() classes = session.query(AssetClass).all() for item in classes: print(item)
Lists all asset classes
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L83-L88
MisterY/asset-allocation
asset_allocation/assetclass_cli.py
my_import
def my_import(file): """ Import Asset Class(es) from a .csv file """ # , help="The path to the CSV file to import. The first row must contain column names." lines = None with open(file) as csv_file: lines = csv_file.readlines() # Header, the first line. header = lines[0] lines.remov...
python
def my_import(file): """ Import Asset Class(es) from a .csv file """ # , help="The path to the CSV file to import. The first row must contain column names." lines = None with open(file) as csv_file: lines = csv_file.readlines() # Header, the first line. header = lines[0] lines.remov...
Import Asset Class(es) from a .csv file
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L93-L121
MisterY/asset-allocation
asset_allocation/assetclass_cli.py
tree
def tree(): """ Display a tree of asset classes """ session = AppAggregate().open_session() classes = session.query(AssetClass).all() # Get the root classes root = [] for ac in classes: if ac.parentid is None: root.append(ac) # logger.debug(ac.parentid) # header ...
python
def tree(): """ Display a tree of asset classes """ session = AppAggregate().open_session() classes = session.query(AssetClass).all() # Get the root classes root = [] for ac in classes: if ac.parentid is None: root.append(ac) # logger.debug(ac.parentid) # header ...
Display a tree of asset classes
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L126-L141
MisterY/asset-allocation
asset_allocation/assetclass_cli.py
print_item_with_children
def print_item_with_children(ac, classes, level): """ Print the given item and all children items """ print_row(ac.id, ac.name, f"{ac.allocation:,.2f}", level) print_children_recursively(classes, ac, level + 1)
python
def print_item_with_children(ac, classes, level): """ Print the given item and all children items """ print_row(ac.id, ac.name, f"{ac.allocation:,.2f}", level) print_children_recursively(classes, ac, level + 1)
Print the given item and all children items
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L143-L146
MisterY/asset-allocation
asset_allocation/assetclass_cli.py
print_children_recursively
def print_children_recursively(all_items, for_item, level): """ Print asset classes recursively """ children = [child for child in all_items if child.parentid == for_item.id] for child in children: #message = f"{for_item.name}({for_item.id}) is a parent to {child.name}({child.id})" indent = ...
python
def print_children_recursively(all_items, for_item, level): """ Print asset classes recursively """ children = [child for child in all_items if child.parentid == for_item.id] for child in children: #message = f"{for_item.name}({for_item.id}) is a parent to {child.name}({child.id})" indent = ...
Print asset classes recursively
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L148-L158
MisterY/asset-allocation
asset_allocation/assetclass_cli.py
print_row
def print_row(*argv): """ Print one row of data """ #for i in range(0, len(argv)): # row += f"{argv[i]}" # columns row = "" # id row += f"{argv[0]:<3}" # name row += f" {argv[1]:<13}" # allocation row += f" {argv[2]:>5}" # level #row += f"{argv[3]}" print(row...
python
def print_row(*argv): """ Print one row of data """ #for i in range(0, len(argv)): # row += f"{argv[i]}" # columns row = "" # id row += f"{argv[0]:<3}" # name row += f" {argv[1]:<13}" # allocation row += f" {argv[2]:>5}" # level #row += f"{argv[3]}" print(row...
Print one row of data
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/assetclass_cli.py#L160-L175
dcwatson/bbcode
bbcode.py
render_html
def render_html(input_text, **context): """ A module-level convenience method that creates a default bbcode parser, and renders the input string as HTML. """ global g_parser if g_parser is None: g_parser = Parser() return g_parser.format(input_text, **context)
python
def render_html(input_text, **context): """ A module-level convenience method that creates a default bbcode parser, and renders the input string as HTML. """ global g_parser if g_parser is None: g_parser = Parser() return g_parser.format(input_text, **context)
A module-level convenience method that creates a default bbcode parser, and renders the input string as HTML.
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L604-L612
dcwatson/bbcode
bbcode.py
Parser.add_formatter
def add_formatter(self, tag_name, render_func, **kwargs): """ Installs a render function for the specified tag name. The render function should have the following signature: def render(tag_name, value, options, parent, context) The arguments are as follows: tag...
python
def add_formatter(self, tag_name, render_func, **kwargs): """ Installs a render function for the specified tag name. The render function should have the following signature: def render(tag_name, value, options, parent, context) The arguments are as follows: tag...
Installs a render function for the specified tag name. The render function should have the following signature: def render(tag_name, value, options, parent, context) The arguments are as follows: tag_name The name of the tag being rendered. value ...
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L113-L136
dcwatson/bbcode
bbcode.py
Parser.add_simple_formatter
def add_simple_formatter(self, tag_name, format_string, **kwargs): """ Installs a formatter that takes the tag options dictionary, puts a value key in it, and uses it as a format dictionary to the given format string. """ def _render(name, value, options, parent, context): ...
python
def add_simple_formatter(self, tag_name, format_string, **kwargs): """ Installs a formatter that takes the tag options dictionary, puts a value key in it, and uses it as a format dictionary to the given format string. """ def _render(name, value, options, parent, context): ...
Installs a formatter that takes the tag options dictionary, puts a value key in it, and uses it as a format dictionary to the given format string.
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L138-L149
dcwatson/bbcode
bbcode.py
Parser.install_default_formatters
def install_default_formatters(self): """ Installs default formatters for the following tags: b, i, u, s, list (and \*), quote, code, center, color, url """ self.add_simple_formatter('b', '<strong>%(value)s</strong>') self.add_simple_formatter('i', '<em>%(value)s</em...
python
def install_default_formatters(self): """ Installs default formatters for the following tags: b, i, u, s, list (and \*), quote, code, center, color, url """ self.add_simple_formatter('b', '<strong>%(value)s</strong>') self.add_simple_formatter('i', '<em>%(value)s</em...
Installs default formatters for the following tags: b, i, u, s, list (and \*), quote, code, center, color, url
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L151-L220
dcwatson/bbcode
bbcode.py
Parser._replace
def _replace(self, data, replacements): """ Given a list of 2-tuples (find, repl) this function performs all replacements on the input and returns the result. """ for find, repl in replacements: data = data.replace(find, repl) return data
python
def _replace(self, data, replacements): """ Given a list of 2-tuples (find, repl) this function performs all replacements on the input and returns the result. """ for find, repl in replacements: data = data.replace(find, repl) return data
Given a list of 2-tuples (find, repl) this function performs all replacements on the input and returns the result.
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L222-L229
dcwatson/bbcode
bbcode.py
Parser._newline_tokenize
def _newline_tokenize(self, data): """ Given a string that does not contain any tags, this function will return a list of NEWLINE and DATA tokens such that if you concatenate their data, you will have the original string. """ parts = data.split('\n') tokens = [] ...
python
def _newline_tokenize(self, data): """ Given a string that does not contain any tags, this function will return a list of NEWLINE and DATA tokens such that if you concatenate their data, you will have the original string. """ parts = data.split('\n') tokens = [] ...
Given a string that does not contain any tags, this function will return a list of NEWLINE and DATA tokens such that if you concatenate their data, you will have the original string.
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L231-L244
dcwatson/bbcode
bbcode.py
Parser._parse_opts
def _parse_opts(self, data): """ Given a tag string, this function will parse any options out of it and return a tuple of (tag_name, options_dict). Options may be quoted in order to preserve spaces, and free-standing options are allowed. The tag name itself may also serve as an o...
python
def _parse_opts(self, data): """ Given a tag string, this function will parse any options out of it and return a tuple of (tag_name, options_dict). Options may be quoted in order to preserve spaces, and free-standing options are allowed. The tag name itself may also serve as an o...
Given a tag string, this function will parse any options out of it and return a tuple of (tag_name, options_dict). Options may be quoted in order to preserve spaces, and free-standing options are allowed. The tag name itself may also serve as an option if it is immediately followed by an equal ...
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L246-L324
dcwatson/bbcode
bbcode.py
Parser._parse_tag
def _parse_tag(self, tag): """ Given a tag string (characters enclosed by []), this function will parse any options and return a tuple of the form: (valid, tag_name, closer, options) """ if not tag.startswith(self.tag_opener) or not tag.endswith(self.tag_closer) or ('...
python
def _parse_tag(self, tag): """ Given a tag string (characters enclosed by []), this function will parse any options and return a tuple of the form: (valid, tag_name, closer, options) """ if not tag.startswith(self.tag_opener) or not tag.endswith(self.tag_closer) or ('...
Given a tag string (characters enclosed by []), this function will parse any options and return a tuple of the form: (valid, tag_name, closer, options)
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L326-L345
dcwatson/bbcode
bbcode.py
Parser._tag_extent
def _tag_extent(self, data, start): """ Finds the extent of a tag, accounting for option quoting and new tags starting before the current one closes. Returns (found_close, end_pos) where valid is False if another tag started before this one closed. """ in_quote = False qu...
python
def _tag_extent(self, data, start): """ Finds the extent of a tag, accounting for option quoting and new tags starting before the current one closes. Returns (found_close, end_pos) where valid is False if another tag started before this one closed. """ in_quote = False qu...
Finds the extent of a tag, accounting for option quoting and new tags starting before the current one closes. Returns (found_close, end_pos) where valid is False if another tag started before this one closed.
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L347-L370
dcwatson/bbcode
bbcode.py
Parser.tokenize
def tokenize(self, data): """ Tokenizes the given string. A token is a 4-tuple of the form: (token_type, tag_name, tag_options, token_text) token_type One of: TOKEN_TAG_START, TOKEN_TAG_END, TOKEN_NEWLINE, TOKEN_DATA tag_name The name...
python
def tokenize(self, data): """ Tokenizes the given string. A token is a 4-tuple of the form: (token_type, tag_name, tag_options, token_text) token_type One of: TOKEN_TAG_START, TOKEN_TAG_END, TOKEN_NEWLINE, TOKEN_DATA tag_name The name...
Tokenizes the given string. A token is a 4-tuple of the form: (token_type, tag_name, tag_options, token_text) token_type One of: TOKEN_TAG_START, TOKEN_TAG_END, TOKEN_NEWLINE, TOKEN_DATA tag_name The name of the tag if token_type=TOKEN_TAG_*, otherwi...
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L372-L426
dcwatson/bbcode
bbcode.py
Parser._find_closing_token
def _find_closing_token(self, tag, tokens, pos): """ Given the current tag options, a list of tokens, and the current position in the token list, this function will find the position of the closing token associated with the specified tag. This may be a closing tag, a newline, or ...
python
def _find_closing_token(self, tag, tokens, pos): """ Given the current tag options, a list of tokens, and the current position in the token list, this function will find the position of the closing token associated with the specified tag. This may be a closing tag, a newline, or ...
Given the current tag options, a list of tokens, and the current position in the token list, this function will find the position of the closing token associated with the specified tag. This may be a closing tag, a newline, or simply the end of the list (to ensure tags are closed). This function...
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L428-L471
dcwatson/bbcode
bbcode.py
Parser._link_replace
def _link_replace(self, match, **context): """ Callback for re.sub to replace link text with markup. Turns out using a callback function is actually faster than using backrefs, plus this lets us provide a hook for user customization. linker_takes_context=True means that the linker gets p...
python
def _link_replace(self, match, **context): """ Callback for re.sub to replace link text with markup. Turns out using a callback function is actually faster than using backrefs, plus this lets us provide a hook for user customization. linker_takes_context=True means that the linker gets p...
Callback for re.sub to replace link text with markup. Turns out using a callback function is actually faster than using backrefs, plus this lets us provide a hook for user customization. linker_takes_context=True means that the linker gets passed context like a standard format function.
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L473-L490
dcwatson/bbcode
bbcode.py
Parser._transform
def _transform(self, data, escape_html, replace_links, replace_cosmetic, transform_newlines, **context): """ Transforms the input string based on the options specified, taking into account whether the option is enabled globally for this parser. """ url_matches = {} if sel...
python
def _transform(self, data, escape_html, replace_links, replace_cosmetic, transform_newlines, **context): """ Transforms the input string based on the options specified, taking into account whether the option is enabled globally for this parser. """ url_matches = {} if sel...
Transforms the input string based on the options specified, taking into account whether the option is enabled globally for this parser.
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L492-L523
dcwatson/bbcode
bbcode.py
Parser.format
def format(self, data, **context): """ Formats the input text using any installed renderers. Any context keyword arguments given here will be passed along to the render functions as a context dictionary. """ tokens = self.tokenize(data) full_context = self.default_context...
python
def format(self, data, **context): """ Formats the input text using any installed renderers. Any context keyword arguments given here will be passed along to the render functions as a context dictionary. """ tokens = self.tokenize(data) full_context = self.default_context...
Formats the input text using any installed renderers. Any context keyword arguments given here will be passed along to the render functions as a context dictionary.
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L578-L586
dcwatson/bbcode
bbcode.py
Parser.strip
def strip(self, data, strip_newlines=False): """ Strips out any tags from the input text, using the same tokenization as the formatter. """ text = [] for token_type, tag_name, tag_opts, token_text in self.tokenize(data): if token_type == self.TOKEN_DATA: ...
python
def strip(self, data, strip_newlines=False): """ Strips out any tags from the input text, using the same tokenization as the formatter. """ text = [] for token_type, tag_name, tag_opts, token_text in self.tokenize(data): if token_type == self.TOKEN_DATA: ...
Strips out any tags from the input text, using the same tokenization as the formatter.
https://github.com/dcwatson/bbcode/blob/eb6f7ff140a78ddb1641102d7382479c4d7c1c78/bbcode.py#L588-L598
astroML/gatspy
gatspy/periodic/naive_multiband.py
mode_in_range
def mode_in_range(a, axis=0, tol=1E-3): """Find the mode of values to within a certain range""" a_trunc = a // tol vals, counts = mode(a_trunc, axis) mask = (a_trunc == vals) # mean of each row return np.sum(a * mask, axis) / np.sum(mask, axis)
python
def mode_in_range(a, axis=0, tol=1E-3): """Find the mode of values to within a certain range""" a_trunc = a // tol vals, counts = mode(a_trunc, axis) mask = (a_trunc == vals) # mean of each row return np.sum(a * mask, axis) / np.sum(mask, axis)
Find the mode of values to within a certain range
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/naive_multiband.py#L18-L24
astroML/gatspy
gatspy/periodic/naive_multiband.py
NaiveMultiband.scores
def scores(self, periods): """Compute the scores under the various models Parameters ---------- periods : array_like array of periods at which to compute scores Returns ------- scores : dict Dictionary of scores. Dictionary keys are the u...
python
def scores(self, periods): """Compute the scores under the various models Parameters ---------- periods : array_like array of periods at which to compute scores Returns ------- scores : dict Dictionary of scores. Dictionary keys are the u...
Compute the scores under the various models Parameters ---------- periods : array_like array of periods at which to compute scores Returns ------- scores : dict Dictionary of scores. Dictionary keys are the unique filter names passed ...
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/naive_multiband.py#L78-L93
astroML/gatspy
gatspy/periodic/naive_multiband.py
NaiveMultiband.best_periods
def best_periods(self): """Compute the scores under the various models Parameters ---------- periods : array_like array of periods at which to compute scores Returns ------- best_periods : dict Dictionary of best periods. Dictionary keys ...
python
def best_periods(self): """Compute the scores under the various models Parameters ---------- periods : array_like array of periods at which to compute scores Returns ------- best_periods : dict Dictionary of best periods. Dictionary keys ...
Compute the scores under the various models Parameters ---------- periods : array_like array of periods at which to compute scores Returns ------- best_periods : dict Dictionary of best periods. Dictionary keys are the unique filter n...
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/naive_multiband.py#L95-L113
astroML/gatspy
gatspy/periodic/modeler.py
PeriodicModeler.fit
def fit(self, t, y, dy=None): """Fit the multiterm Periodogram model to the data. Parameters ---------- t : array_like, one-dimensional sequence of observation times y : array_like, one-dimensional sequence of observed values dy : float or array_l...
python
def fit(self, t, y, dy=None): """Fit the multiterm Periodogram model to the data. Parameters ---------- t : array_like, one-dimensional sequence of observation times y : array_like, one-dimensional sequence of observed values dy : float or array_l...
Fit the multiterm Periodogram model to the data. Parameters ---------- t : array_like, one-dimensional sequence of observation times y : array_like, one-dimensional sequence of observed values dy : float or array_like (optional) errors on obse...
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L27-L51
astroML/gatspy
gatspy/periodic/modeler.py
PeriodicModeler.predict
def predict(self, t, period=None): """Compute the best-fit model at ``t`` for a given period Parameters ---------- t : float or array_like times at which to predict period : float (optional) The period at which to compute the model. If not specified, it ...
python
def predict(self, t, period=None): """Compute the best-fit model at ``t`` for a given period Parameters ---------- t : float or array_like times at which to predict period : float (optional) The period at which to compute the model. If not specified, it ...
Compute the best-fit model at ``t`` for a given period Parameters ---------- t : float or array_like times at which to predict period : float (optional) The period at which to compute the model. If not specified, it will be computed via the optimizer ...
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L53-L73
astroML/gatspy
gatspy/periodic/modeler.py
PeriodicModeler.score_frequency_grid
def score_frequency_grid(self, f0, df, N): """Compute the score on a frequency grid. Some models can compute results faster if the inputs are passed in this manner. Parameters ---------- f0, df, N : (float, float, int) parameters describing the frequency gri...
python
def score_frequency_grid(self, f0, df, N): """Compute the score on a frequency grid. Some models can compute results faster if the inputs are passed in this manner. Parameters ---------- f0, df, N : (float, float, int) parameters describing the frequency gri...
Compute the score on a frequency grid. Some models can compute results faster if the inputs are passed in this manner. Parameters ---------- f0, df, N : (float, float, int) parameters describing the frequency grid freq = f0 + df * arange(N) Note that the...
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L75-L92
astroML/gatspy
gatspy/periodic/modeler.py
PeriodicModeler.periodogram_auto
def periodogram_auto(self, oversampling=5, nyquist_factor=3, return_periods=True): """Compute the periodogram on an automatically-determined grid This function uses heuristic arguments to choose a suitable frequency grid for the data. Note that depending on the data win...
python
def periodogram_auto(self, oversampling=5, nyquist_factor=3, return_periods=True): """Compute the periodogram on an automatically-determined grid This function uses heuristic arguments to choose a suitable frequency grid for the data. Note that depending on the data win...
Compute the periodogram on an automatically-determined grid This function uses heuristic arguments to choose a suitable frequency grid for the data. Note that depending on the data window function, the model may be sensitive to periodicity at higher frequencies than this function return...
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L94-L127
astroML/gatspy
gatspy/periodic/modeler.py
PeriodicModeler.score
def score(self, periods=None): """Compute the periodogram for the given period or periods Parameters ---------- periods : float or array_like Array of periods at which to compute the periodogram. Returns ------- scores : np.ndarray Array ...
python
def score(self, periods=None): """Compute the periodogram for the given period or periods Parameters ---------- periods : float or array_like Array of periods at which to compute the periodogram. Returns ------- scores : np.ndarray Array ...
Compute the periodogram for the given period or periods Parameters ---------- periods : float or array_like Array of periods at which to compute the periodogram. Returns ------- scores : np.ndarray Array of normalized powers (between 0 and 1) for...
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L129-L144
astroML/gatspy
gatspy/periodic/modeler.py
PeriodicModeler.best_period
def best_period(self): """Lazy evaluation of the best period given the model""" if self._best_period is None: self._best_period = self._calc_best_period() return self._best_period
python
def best_period(self): """Lazy evaluation of the best period given the model""" if self._best_period is None: self._best_period = self._calc_best_period() return self._best_period
Lazy evaluation of the best period given the model
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L149-L153
astroML/gatspy
gatspy/periodic/modeler.py
PeriodicModeler.find_best_periods
def find_best_periods(self, n_periods=5, return_scores=False): """Find the top several best periods for the model""" return self.optimizer.find_best_periods(self, n_periods, return_scores=return_scores)
python
def find_best_periods(self, n_periods=5, return_scores=False): """Find the top several best periods for the model""" return self.optimizer.find_best_periods(self, n_periods, return_scores=return_scores)
Find the top several best periods for the model
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L155-L158
astroML/gatspy
gatspy/periodic/modeler.py
PeriodicModelerMultiband.fit
def fit(self, t, y, dy=None, filts=0): """Fit the multiterm Periodogram model to the data. Parameters ---------- t : array_like, one-dimensional sequence of observation times y : array_like, one-dimensional sequence of observed values dy : float o...
python
def fit(self, t, y, dy=None, filts=0): """Fit the multiterm Periodogram model to the data. Parameters ---------- t : array_like, one-dimensional sequence of observation times y : array_like, one-dimensional sequence of observed values dy : float o...
Fit the multiterm Periodogram model to the data. Parameters ---------- t : array_like, one-dimensional sequence of observation times y : array_like, one-dimensional sequence of observed values dy : float or array_like (optional) errors on obse...
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L186-L214
astroML/gatspy
gatspy/periodic/modeler.py
PeriodicModelerMultiband.predict
def predict(self, t, filts, period=None): """Compute the best-fit model at ``t`` for a given period Parameters ---------- t : float or array_like times at which to predict filts : array_like (optional) the array specifying the filter/bandpass for each obs...
python
def predict(self, t, filts, period=None): """Compute the best-fit model at ``t`` for a given period Parameters ---------- t : float or array_like times at which to predict filts : array_like (optional) the array specifying the filter/bandpass for each obs...
Compute the best-fit model at ``t`` for a given period Parameters ---------- t : float or array_like times at which to predict filts : array_like (optional) the array specifying the filter/bandpass for each observation. This is used only in multiband ...
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/modeler.py#L216-L247
astroML/gatspy
gatspy/periodic/_least_squares_mixin.py
LeastSquaresMixin._construct_X_M
def _construct_X_M(self, omega, **kwargs): """Construct the weighted normal matrix of the problem""" X = self._construct_X(omega, weighted=True, **kwargs) M = np.dot(X.T, X) if getattr(self, 'regularization', None) is not None: diag = M.ravel(order='K')[::M.shape[0] + 1] ...
python
def _construct_X_M(self, omega, **kwargs): """Construct the weighted normal matrix of the problem""" X = self._construct_X(omega, weighted=True, **kwargs) M = np.dot(X.T, X) if getattr(self, 'regularization', None) is not None: diag = M.ravel(order='K')[::M.shape[0] + 1] ...
Construct the weighted normal matrix of the problem
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/_least_squares_mixin.py#L11-L23
astroML/gatspy
gatspy/periodic/_least_squares_mixin.py
LeastSquaresMixin._compute_ymean
def _compute_ymean(self, **kwargs): """Compute the (weighted) mean of the y data""" y = np.asarray(kwargs.get('y', self.y)) dy = np.asarray(kwargs.get('dy', self.dy)) if dy.size == 1: return np.mean(y) else: return np.average(y, weights=1 / dy ** 2)
python
def _compute_ymean(self, **kwargs): """Compute the (weighted) mean of the y data""" y = np.asarray(kwargs.get('y', self.y)) dy = np.asarray(kwargs.get('dy', self.dy)) if dy.size == 1: return np.mean(y) else: return np.average(y, weights=1 / dy ** 2)
Compute the (weighted) mean of the y data
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/_least_squares_mixin.py#L25-L33
astroML/gatspy
gatspy/periodic/lomb_scargle.py
LombScargle._construct_X
def _construct_X(self, omega, weighted=True, **kwargs): """Construct the design matrix for the problem""" t = kwargs.get('t', self.t) dy = kwargs.get('dy', self.dy) fit_offset = kwargs.get('fit_offset', self.fit_offset) if fit_offset: offsets = [np.ones(len(t))] ...
python
def _construct_X(self, omega, weighted=True, **kwargs): """Construct the design matrix for the problem""" t = kwargs.get('t', self.t) dy = kwargs.get('dy', self.dy) fit_offset = kwargs.get('fit_offset', self.fit_offset) if fit_offset: offsets = [np.ones(len(t))] ...
Construct the design matrix for the problem
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/lomb_scargle.py#L92-L110
astroML/gatspy
gatspy/periodic/template_modeler.py
BaseTemplateModeler._interpolated_template
def _interpolated_template(self, templateid): """Return an interpolator for the given template""" phase, y = self._get_template_by_id(templateid) # double-check that phase ranges from 0 to 1 assert phase.min() >= 0 assert phase.max() <= 1 # at the start and end points, ...
python
def _interpolated_template(self, templateid): """Return an interpolator for the given template""" phase, y = self._get_template_by_id(templateid) # double-check that phase ranges from 0 to 1 assert phase.min() >= 0 assert phase.max() <= 1 # at the start and end points, ...
Return an interpolator for the given template
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/template_modeler.py#L39-L53
astroML/gatspy
gatspy/periodic/template_modeler.py
BaseTemplateModeler._eval_templates
def _eval_templates(self, period): """Evaluate the best template for the given period""" theta_best = [self._optimize(period, tmpid) for tmpid, _ in enumerate(self.templates)] chi2 = [self._chi2(theta, period, tmpid) for tmpid, theta in enumerate(theta_best)...
python
def _eval_templates(self, period): """Evaluate the best template for the given period""" theta_best = [self._optimize(period, tmpid) for tmpid, _ in enumerate(self.templates)] chi2 = [self._chi2(theta, period, tmpid) for tmpid, theta in enumerate(theta_best)...
Evaluate the best template for the given period
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/template_modeler.py#L77-L84
astroML/gatspy
gatspy/periodic/template_modeler.py
BaseTemplateModeler._model
def _model(self, t, theta, period, tmpid): """Compute model at t for the given parameters, period, & template""" template = self.templates[tmpid] phase = (t / period - theta[2]) % 1 return theta[0] + theta[1] * template(phase)
python
def _model(self, t, theta, period, tmpid): """Compute model at t for the given parameters, period, & template""" template = self.templates[tmpid] phase = (t / period - theta[2]) % 1 return theta[0] + theta[1] * template(phase)
Compute model at t for the given parameters, period, & template
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/template_modeler.py#L86-L90
astroML/gatspy
gatspy/periodic/template_modeler.py
BaseTemplateModeler._chi2
def _chi2(self, theta, period, tmpid, return_gradient=False): """ Compute the chi2 for the given parameters, period, & template Optionally return the gradient for faster optimization """ template = self.templates[tmpid] phase = (self.t / period - theta[2]) % 1 mo...
python
def _chi2(self, theta, period, tmpid, return_gradient=False): """ Compute the chi2 for the given parameters, period, & template Optionally return the gradient for faster optimization """ template = self.templates[tmpid] phase = (self.t / period - theta[2]) % 1 mo...
Compute the chi2 for the given parameters, period, & template Optionally return the gradient for faster optimization
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/template_modeler.py#L92-L111
astroML/gatspy
gatspy/periodic/template_modeler.py
BaseTemplateModeler._optimize
def _optimize(self, period, tmpid, use_gradient=True): """Optimize the model for the given period & template""" theta_0 = [self.y.min(), self.y.max() - self.y.min(), 0] result = minimize(self._chi2, theta_0, jac=bool(use_gradient), bounds=[(None, None), (0, None), (None...
python
def _optimize(self, period, tmpid, use_gradient=True): """Optimize the model for the given period & template""" theta_0 = [self.y.min(), self.y.max() - self.y.min(), 0] result = minimize(self._chi2, theta_0, jac=bool(use_gradient), bounds=[(None, None), (0, None), (None...
Optimize the model for the given period & template
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/template_modeler.py#L113-L119
astroML/gatspy
gatspy/periodic/optimizer.py
LinearScanOptimizer.find_best_periods
def find_best_periods(self, model, n_periods=5, return_scores=False): """Find the `n_periods` best periods in the model""" # compute the estimated peak width from the data range tmin, tmax = np.min(model.t), np.max(model.t) width = 2 * np.pi / (tmax - tmin) # raise a ValueError...
python
def find_best_periods(self, model, n_periods=5, return_scores=False): """Find the `n_periods` best periods in the model""" # compute the estimated peak width from the data range tmin, tmax = np.min(model.t), np.max(model.t) width = 2 * np.pi / (tmax - tmin) # raise a ValueError...
Find the `n_periods` best periods in the model
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/optimizer.py#L74-L156
astroML/gatspy
gatspy/periodic/lomb_scargle_fast.py
factorial
def factorial(N): """Compute the factorial of N. If N <= 10, use a fast lookup table; otherwise use scipy.special.factorial """ if N < len(FACTORIALS): return FACTORIALS[N] else: from scipy import special return int(special.factorial(N))
python
def factorial(N): """Compute the factorial of N. If N <= 10, use a fast lookup table; otherwise use scipy.special.factorial """ if N < len(FACTORIALS): return FACTORIALS[N] else: from scipy import special return int(special.factorial(N))
Compute the factorial of N. If N <= 10, use a fast lookup table; otherwise use scipy.special.factorial
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/lomb_scargle_fast.py#L17-L25
astroML/gatspy
gatspy/periodic/lomb_scargle_fast.py
bitceil
def bitceil(N): """ Find the bit (i.e. power of 2) immediately greater than or equal to N Note: this works for numbers up to 2 ** 64. Roughly equivalent to int(2 ** np.ceil(np.log2(N))) """ # Note: for Python 2.7 and 3.x, this is faster: # return 1 << int(N - 1).bit_length() N = int(N) ...
python
def bitceil(N): """ Find the bit (i.e. power of 2) immediately greater than or equal to N Note: this works for numbers up to 2 ** 64. Roughly equivalent to int(2 ** np.ceil(np.log2(N))) """ # Note: for Python 2.7 and 3.x, this is faster: # return 1 << int(N - 1).bit_length() N = int(N) ...
Find the bit (i.e. power of 2) immediately greater than or equal to N Note: this works for numbers up to 2 ** 64. Roughly equivalent to int(2 ** np.ceil(np.log2(N)))
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/lomb_scargle_fast.py#L28-L40
astroML/gatspy
gatspy/periodic/lomb_scargle_fast.py
extirpolate
def extirpolate(x, y, N=None, M=4): """ Extirpolate the values (x, y) onto an integer grid range(N), using lagrange polynomial weights on the M nearest points. Parameters ---------- x : array_like array of abscissas y : array_like array of ordinates N : int numbe...
python
def extirpolate(x, y, N=None, M=4): """ Extirpolate the values (x, y) onto an integer grid range(N), using lagrange polynomial weights on the M nearest points. Parameters ---------- x : array_like array of abscissas y : array_like array of ordinates N : int numbe...
Extirpolate the values (x, y) onto an integer grid range(N), using lagrange polynomial weights on the M nearest points. Parameters ---------- x : array_like array of abscissas y : array_like array of ordinates N : int number of integer bins to use. For best performance, ...
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/lomb_scargle_fast.py#L43-L107
astroML/gatspy
gatspy/periodic/lomb_scargle_fast.py
trig_sum
def trig_sum(t, h, df, N, f0=0, freq_factor=1, oversampling=5, use_fft=True, Mfft=4): """Compute (approximate) trigonometric sums for a number of frequencies This routine computes weighted sine and cosine sums: S_j = sum_i { h_i * sin(2 pi * f_j * t_i) } C_j = sum_i { h_i * cos(2 ...
python
def trig_sum(t, h, df, N, f0=0, freq_factor=1, oversampling=5, use_fft=True, Mfft=4): """Compute (approximate) trigonometric sums for a number of frequencies This routine computes weighted sine and cosine sums: S_j = sum_i { h_i * sin(2 pi * f_j * t_i) } C_j = sum_i { h_i * cos(2 ...
Compute (approximate) trigonometric sums for a number of frequencies This routine computes weighted sine and cosine sums: S_j = sum_i { h_i * sin(2 pi * f_j * t_i) } C_j = sum_i { h_i * cos(2 pi * f_j * t_i) } Where f_j = freq_factor * (f0 + j * df) for the values j in 1 ... N. The sums c...
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/lomb_scargle_fast.py#L110-L187
astroML/gatspy
gatspy/periodic/lomb_scargle_fast.py
lomb_scargle_fast
def lomb_scargle_fast(t, y, dy=1, f0=0, df=None, Nf=None, center_data=True, fit_offset=True, use_fft=True, freq_oversampling=5, nyquist_factor=2, trig_sum_kwds=None): """Compute a lomb-scargle periodogram for the given data This implements both ...
python
def lomb_scargle_fast(t, y, dy=1, f0=0, df=None, Nf=None, center_data=True, fit_offset=True, use_fft=True, freq_oversampling=5, nyquist_factor=2, trig_sum_kwds=None): """Compute a lomb-scargle periodogram for the given data This implements both ...
Compute a lomb-scargle periodogram for the given data This implements both an O[N^2] method if use_fft==False, or an O[NlogN] method if use_fft==True. Parameters ---------- t, y, dy : array_like times, values, and errors of the data points. These should be broadcastable to the same...
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/periodic/lomb_scargle_fast.py#L190-L330
astroML/gatspy
gatspy/datasets/rrlyrae_generated.py
RRLyraeGenerated.observed
def observed(self, band, corrected=True): """Return observed values in the given band Parameters ---------- band : str desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z'] corrected : bool (optional) If true, correct for extinction Return...
python
def observed(self, band, corrected=True): """Return observed values in the given band Parameters ---------- band : str desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z'] corrected : bool (optional) If true, correct for extinction Return...
Return observed values in the given band Parameters ---------- band : str desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z'] corrected : bool (optional) If true, correct for extinction Returns ------- t, mag, dmag : ndarrays ...
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae_generated.py#L77-L102
astroML/gatspy
gatspy/datasets/rrlyrae_generated.py
RRLyraeGenerated.generated
def generated(self, band, t, err=None, corrected=True): """Return generated magnitudes in the specified band Parameters ---------- band : str desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z'] t : array_like array of times (in days) err ...
python
def generated(self, band, t, err=None, corrected=True): """Return generated magnitudes in the specified band Parameters ---------- band : str desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z'] t : array_like array of times (in days) err ...
Return generated magnitudes in the specified band Parameters ---------- band : str desired bandpass: should be one of ['u', 'g', 'r', 'i', 'z'] t : array_like array of times (in days) err : float or array_like gaussian error in observations ...
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae_generated.py#L104-L146
astroML/gatspy
gatspy/datasets/rrlyrae.py
_get_download_or_cache
def _get_download_or_cache(filename, data_home=None, url=SESAR_RRLYRAE_URL, force_download=False): """Private utility to download and/or load data from disk cache.""" # Import here so astroML is not required at package level from astroML.datasets.tools i...
python
def _get_download_or_cache(filename, data_home=None, url=SESAR_RRLYRAE_URL, force_download=False): """Private utility to download and/or load data from disk cache.""" # Import here so astroML is not required at package level from astroML.datasets.tools i...
Private utility to download and/or load data from disk cache.
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L28-L48
astroML/gatspy
gatspy/datasets/rrlyrae.py
fetch_rrlyrae
def fetch_rrlyrae(partial=False, **kwargs): """Fetch RR Lyrae light curves from Sesar 2010 Parameters ---------- partial : bool (optional) If true, return the partial dataset (reduced to 1 band per night) Returns ------- rrlyrae : :class:`RRLyraeLC` object This object conta...
python
def fetch_rrlyrae(partial=False, **kwargs): """Fetch RR Lyrae light curves from Sesar 2010 Parameters ---------- partial : bool (optional) If true, return the partial dataset (reduced to 1 band per night) Returns ------- rrlyrae : :class:`RRLyraeLC` object This object conta...
Fetch RR Lyrae light curves from Sesar 2010 Parameters ---------- partial : bool (optional) If true, return the partial dataset (reduced to 1 band per night) Returns ------- rrlyrae : :class:`RRLyraeLC` object This object contains pointers to the RR Lyrae data. Other Param...
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L343-L389
astroML/gatspy
gatspy/datasets/rrlyrae.py
fetch_rrlyrae_lc_params
def fetch_rrlyrae_lc_params(**kwargs): """Fetch data from table 2 of Sesar 2010 This table includes observationally-derived parameters for all the Sesar 2010 lightcurves. """ save_loc = _get_download_or_cache('table2.dat.gz', **kwargs) dtype = [('id', 'i'), ('type', 'S2'), ('P', 'f'), ...
python
def fetch_rrlyrae_lc_params(**kwargs): """Fetch data from table 2 of Sesar 2010 This table includes observationally-derived parameters for all the Sesar 2010 lightcurves. """ save_loc = _get_download_or_cache('table2.dat.gz', **kwargs) dtype = [('id', 'i'), ('type', 'S2'), ('P', 'f'), ...
Fetch data from table 2 of Sesar 2010 This table includes observationally-derived parameters for all the Sesar 2010 lightcurves.
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L392-L407
astroML/gatspy
gatspy/datasets/rrlyrae.py
fetch_rrlyrae_fitdata
def fetch_rrlyrae_fitdata(**kwargs): """Fetch data from table 3 of Sesar 2010 This table includes parameters derived from template fits to all the Sesar 2010 lightcurves. """ save_loc = _get_download_or_cache('table3.dat.gz', **kwargs) dtype = [('id', 'i'), ('RA', 'f'), ('DEC', 'f'), ('rExt', ...
python
def fetch_rrlyrae_fitdata(**kwargs): """Fetch data from table 3 of Sesar 2010 This table includes parameters derived from template fits to all the Sesar 2010 lightcurves. """ save_loc = _get_download_or_cache('table3.dat.gz', **kwargs) dtype = [('id', 'i'), ('RA', 'f'), ('DEC', 'f'), ('rExt', ...
Fetch data from table 3 of Sesar 2010 This table includes parameters derived from template fits to all the Sesar 2010 lightcurves.
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L410-L425
astroML/gatspy
gatspy/datasets/rrlyrae.py
RRLyraeLC.get_lightcurve
def get_lightcurve(self, star_id, return_1d=True): """Get the light curves for the given ID Parameters ---------- star_id : int A valid integer star id representing an object in the dataset return_1d : boolean (default=True) Specify whether to return 1D a...
python
def get_lightcurve(self, star_id, return_1d=True): """Get the light curves for the given ID Parameters ---------- star_id : int A valid integer star id representing an object in the dataset return_1d : boolean (default=True) Specify whether to return 1D a...
Get the light curves for the given ID Parameters ---------- star_id : int A valid integer star id representing an object in the dataset return_1d : boolean (default=True) Specify whether to return 1D arrays of (t, y, dy, filts) or 2D arrays of (t, y, ...
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L125-L173
astroML/gatspy
gatspy/datasets/rrlyrae.py
RRLyraeLC.get_metadata
def get_metadata(self, lcid): """Get the parameters derived from the fit for the given id. This is table 2 of Sesar 2010 """ if self._metadata is None: self._metadata = fetch_rrlyrae_lc_params() i = np.where(self._metadata['id'] == lcid)[0] if len(i) == 0: ...
python
def get_metadata(self, lcid): """Get the parameters derived from the fit for the given id. This is table 2 of Sesar 2010 """ if self._metadata is None: self._metadata = fetch_rrlyrae_lc_params() i = np.where(self._metadata['id'] == lcid)[0] if len(i) == 0: ...
Get the parameters derived from the fit for the given id. This is table 2 of Sesar 2010
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L175-L184
astroML/gatspy
gatspy/datasets/rrlyrae.py
RRLyraeLC.get_obsmeta
def get_obsmeta(self, lcid): """Get the observation metadata for the given id. This is table 3 of Sesar 2010 """ if self._obsdata is None: self._obsdata = fetch_rrlyrae_fitdata() i = np.where(self._obsdata['id'] == lcid)[0] if len(i) == 0: raise Va...
python
def get_obsmeta(self, lcid): """Get the observation metadata for the given id. This is table 3 of Sesar 2010 """ if self._obsdata is None: self._obsdata = fetch_rrlyrae_fitdata() i = np.where(self._obsdata['id'] == lcid)[0] if len(i) == 0: raise Va...
Get the observation metadata for the given id. This is table 3 of Sesar 2010
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L186-L195
astroML/gatspy
gatspy/datasets/rrlyrae.py
RRLyraeTemplates.get_template
def get_template(self, template_id): """Get a particular lightcurve template Parameters ---------- template_id : str id of desired template Returns ------- phase : ndarray array of phases mag : ndarray array of normaliz...
python
def get_template(self, template_id): """Get a particular lightcurve template Parameters ---------- template_id : str id of desired template Returns ------- phase : ndarray array of phases mag : ndarray array of normaliz...
Get a particular lightcurve template Parameters ---------- template_id : str id of desired template Returns ------- phase : ndarray array of phases mag : ndarray array of normalized magnitudes
https://github.com/astroML/gatspy/blob/a8f94082a3f27dfe9cb58165707b883bf28d9223/gatspy/datasets/rrlyrae.py#L322-L340
vkurup/python-tcxparser
tcxparser/tcxparser.py
TCXParser.hr_avg
def hr_avg(self): """Average heart rate of the workout""" hr_data = self.hr_values() return int(sum(hr_data) / len(hr_data))
python
def hr_avg(self): """Average heart rate of the workout""" hr_data = self.hr_values() return int(sum(hr_data) / len(hr_data))
Average heart rate of the workout
https://github.com/vkurup/python-tcxparser/blob/b5bdd86d1e76f842043f28717e261d25025b1a8e/tcxparser/tcxparser.py#L73-L76
vkurup/python-tcxparser
tcxparser/tcxparser.py
TCXParser.pace
def pace(self): """Average pace (mm:ss/km for the workout""" secs_per_km = self.duration / (self.distance / 1000) return time.strftime('%M:%S', time.gmtime(secs_per_km))
python
def pace(self): """Average pace (mm:ss/km for the workout""" secs_per_km = self.duration / (self.distance / 1000) return time.strftime('%M:%S', time.gmtime(secs_per_km))
Average pace (mm:ss/km for the workout
https://github.com/vkurup/python-tcxparser/blob/b5bdd86d1e76f842043f28717e261d25025b1a8e/tcxparser/tcxparser.py#L89-L92
vkurup/python-tcxparser
tcxparser/tcxparser.py
TCXParser.ascent
def ascent(self): """Returns ascent of workout in meters""" total_ascent = 0.0 altitude_data = self.altitude_points() for i in range(len(altitude_data) - 1): diff = altitude_data[i+1] - altitude_data[i] if diff > 0.0: total_ascent += diff r...
python
def ascent(self): """Returns ascent of workout in meters""" total_ascent = 0.0 altitude_data = self.altitude_points() for i in range(len(altitude_data) - 1): diff = altitude_data[i+1] - altitude_data[i] if diff > 0.0: total_ascent += diff r...
Returns ascent of workout in meters
https://github.com/vkurup/python-tcxparser/blob/b5bdd86d1e76f842043f28717e261d25025b1a8e/tcxparser/tcxparser.py#L113-L121
vkurup/python-tcxparser
tcxparser/tcxparser.py
TCXParser.descent
def descent(self): """Returns descent of workout in meters""" total_descent = 0.0 altitude_data = self.altitude_points() for i in range(len(altitude_data) - 1): diff = altitude_data[i+1] - altitude_data[i] if diff < 0.0: total_descent += abs(diff) ...
python
def descent(self): """Returns descent of workout in meters""" total_descent = 0.0 altitude_data = self.altitude_points() for i in range(len(altitude_data) - 1): diff = altitude_data[i+1] - altitude_data[i] if diff < 0.0: total_descent += abs(diff) ...
Returns descent of workout in meters
https://github.com/vkurup/python-tcxparser/blob/b5bdd86d1e76f842043f28717e261d25025b1a8e/tcxparser/tcxparser.py#L124-L132
uktrade/directory-validators
directory_validators/company.py
keywords_special_characters
def keywords_special_characters(keywords): """ Confirms that the keywords don't contain special characters Args: keywords (str) Raises: django.forms.ValidationError """ invalid_chars = '!\"#$%&\'()*+-./:;<=>?@[\\]^_{|}~\t\n' if any(char in invalid_chars for char in keywords...
python
def keywords_special_characters(keywords): """ Confirms that the keywords don't contain special characters Args: keywords (str) Raises: django.forms.ValidationError """ invalid_chars = '!\"#$%&\'()*+-./:;<=>?@[\\]^_{|}~\t\n' if any(char in invalid_chars for char in keywords...
Confirms that the keywords don't contain special characters Args: keywords (str) Raises: django.forms.ValidationError
https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/company.py#L45-L57
uktrade/directory-validators
directory_validators/company.py
image_format
def image_format(value): """ Confirms that the uploaded image is of supported format. Args: value (File): The file with an `image` property containing the image Raises: django.forms.ValidationError """ if value.image.format.upper() not in constants.ALLOWED_IMAGE_FORMATS: ...
python
def image_format(value): """ Confirms that the uploaded image is of supported format. Args: value (File): The file with an `image` property containing the image Raises: django.forms.ValidationError """ if value.image.format.upper() not in constants.ALLOWED_IMAGE_FORMATS: ...
Confirms that the uploaded image is of supported format. Args: value (File): The file with an `image` property containing the image Raises: django.forms.ValidationError
https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/company.py#L60-L73
uktrade/directory-validators
directory_validators/company.py
case_study_social_link_facebook
def case_study_social_link_facebook(value): """ Confirms that the social media url is pointed at the correct domain. Args: value (string): The url to check. Raises: django.forms.ValidationError """ parsed = parse.urlparse(value.lower()) if not parsed.netloc.endswith('face...
python
def case_study_social_link_facebook(value): """ Confirms that the social media url is pointed at the correct domain. Args: value (string): The url to check. Raises: django.forms.ValidationError """ parsed = parse.urlparse(value.lower()) if not parsed.netloc.endswith('face...
Confirms that the social media url is pointed at the correct domain. Args: value (string): The url to check. Raises: django.forms.ValidationError
https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/company.py#L108-L122
uktrade/directory-validators
directory_validators/company.py
case_study_social_link_twitter
def case_study_social_link_twitter(value): """ Confirms that the social media url is pointed at the correct domain. Args: value (string): The url to check. Raises: django.forms.ValidationError """ parsed = parse.urlparse(value.lower()) if not parsed.netloc.endswith('twitt...
python
def case_study_social_link_twitter(value): """ Confirms that the social media url is pointed at the correct domain. Args: value (string): The url to check. Raises: django.forms.ValidationError """ parsed = parse.urlparse(value.lower()) if not parsed.netloc.endswith('twitt...
Confirms that the social media url is pointed at the correct domain. Args: value (string): The url to check. Raises: django.forms.ValidationError
https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/company.py#L125-L139
uktrade/directory-validators
directory_validators/company.py
case_study_social_link_linkedin
def case_study_social_link_linkedin(value): """ Confirms that the social media url is pointed at the correct domain. Args: value (string): The url to check. Raises: django.forms.ValidationError """ parsed = parse.urlparse(value.lower()) if not parsed.netloc.endswith('link...
python
def case_study_social_link_linkedin(value): """ Confirms that the social media url is pointed at the correct domain. Args: value (string): The url to check. Raises: django.forms.ValidationError """ parsed = parse.urlparse(value.lower()) if not parsed.netloc.endswith('link...
Confirms that the social media url is pointed at the correct domain. Args: value (string): The url to check. Raises: django.forms.ValidationError
https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/company.py#L142-L156
uktrade/directory-validators
directory_validators/company.py
no_company_with_insufficient_companies_house_data
def no_company_with_insufficient_companies_house_data(value): """ Confirms that the company number is not for for a company that Companies House does not hold information on. Args: value (string): The company number to check. Raises: django.forms.ValidationError """ for p...
python
def no_company_with_insufficient_companies_house_data(value): """ Confirms that the company number is not for for a company that Companies House does not hold information on. Args: value (string): The company number to check. Raises: django.forms.ValidationError """ for p...
Confirms that the company number is not for for a company that Companies House does not hold information on. Args: value (string): The company number to check. Raises: django.forms.ValidationError
https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/company.py#L179-L196
uktrade/directory-validators
directory_validators/enrolment.py
email_domain_free
def email_domain_free(value): """ Confirms that the email address is not using a free service. @param {str} value @returns {None} @raises AssertionError """ domain = helpers.get_domain_from_email_address(value) if domain.lower() in free_domains: raise ValidationError(MESSAGE_US...
python
def email_domain_free(value): """ Confirms that the email address is not using a free service. @param {str} value @returns {None} @raises AssertionError """ domain = helpers.get_domain_from_email_address(value) if domain.lower() in free_domains: raise ValidationError(MESSAGE_US...
Confirms that the email address is not using a free service. @param {str} value @returns {None} @raises AssertionError
https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/enrolment.py#L43-L54
uktrade/directory-validators
directory_validators/enrolment.py
email_domain_disposable
def email_domain_disposable(value): """ Confirms that the email address is not using a disposable service. @param {str} value @returns {None} @raises AssertionError """ domain = helpers.get_domain_from_email_address(value) if domain.lower() in disposable_domains: raise Validati...
python
def email_domain_disposable(value): """ Confirms that the email address is not using a disposable service. @param {str} value @returns {None} @raises AssertionError """ domain = helpers.get_domain_from_email_address(value) if domain.lower() in disposable_domains: raise Validati...
Confirms that the email address is not using a disposable service. @param {str} value @returns {None} @raises AssertionError
https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/enrolment.py#L57-L68
uktrade/directory-validators
directory_validators/enrolment.py
domestic_mobile_phone_number
def domestic_mobile_phone_number(value): """ Confirms that the phone number is a valid UK phone number. @param {str} value @returns {None} @raises AssertionError """ try: parsed = phonenumbers.parse(value, 'GB') except NumberParseException: pass else: is_mob...
python
def domestic_mobile_phone_number(value): """ Confirms that the phone number is a valid UK phone number. @param {str} value @returns {None} @raises AssertionError """ try: parsed = phonenumbers.parse(value, 'GB') except NumberParseException: pass else: is_mob...
Confirms that the phone number is a valid UK phone number. @param {str} value @returns {None} @raises AssertionError
https://github.com/uktrade/directory-validators/blob/e01f9d2aec683e34d978e4f67ed383ea2f9b85a0/directory_validators/enrolment.py#L71-L88
ruipgil/TrackToTrip
tracktotrip/segment.py
remove_liers
def remove_liers(points): """ Removes obvious noise points Checks time consistency, removing points that appear out of order Args: points (:obj:`list` of :obj:`Point`) Returns: :obj:`list` of :obj:`Point` """ result = [points[0]] for i in range(1, len(points) - 2): ...
python
def remove_liers(points): """ Removes obvious noise points Checks time consistency, removing points that appear out of order Args: points (:obj:`list` of :obj:`Point`) Returns: :obj:`list` of :obj:`Point` """ result = [points[0]] for i in range(1, len(points) - 2): ...
Removes obvious noise points Checks time consistency, removing points that appear out of order Args: points (:obj:`list` of :obj:`Point`) Returns: :obj:`list` of :obj:`Point`
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L20-L39
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.bounds
def bounds(self, thr=0, lower_index=0, upper_index=-1): """ Computes the bounds of the segment, or part of it Args: lower_index (int, optional): Start index. Defaults to 0 upper_index (int, optional): End index. Defaults to 0 Returns: :obj:`tuple` of :obj:`fl...
python
def bounds(self, thr=0, lower_index=0, upper_index=-1): """ Computes the bounds of the segment, or part of it Args: lower_index (int, optional): Start index. Defaults to 0 upper_index (int, optional): End index. Defaults to 0 Returns: :obj:`tuple` of :obj:`fl...
Computes the bounds of the segment, or part of it Args: lower_index (int, optional): Start index. Defaults to 0 upper_index (int, optional): End index. Defaults to 0 Returns: :obj:`tuple` of :obj:`float`: Bounds of the (sub)segment, such that (min_lat...
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L65-L88
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.smooth
def smooth(self, noise, strategy=INVERSE_STRATEGY): """ In-place smoothing See smooth_segment function Args: noise (float): Noise expected strategy (int): Strategy to use. Either smooth.INVERSE_STRATEGY or smooth.EXTRAPOLATE_STRATEGY Returns: ...
python
def smooth(self, noise, strategy=INVERSE_STRATEGY): """ In-place smoothing See smooth_segment function Args: noise (float): Noise expected strategy (int): Strategy to use. Either smooth.INVERSE_STRATEGY or smooth.EXTRAPOLATE_STRATEGY Returns: ...
In-place smoothing See smooth_segment function Args: noise (float): Noise expected strategy (int): Strategy to use. Either smooth.INVERSE_STRATEGY or smooth.EXTRAPOLATE_STRATEGY Returns: :obj:`Segment`
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L101-L119
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.simplify
def simplify(self, eps, max_dist_error, max_speed_error, topology_only=False): """ In-place segment simplification See `drp` and `compression` modules Args: eps (float): Distance threshold for the `drp` function max_dist_error (float): Max distance error, in meters ...
python
def simplify(self, eps, max_dist_error, max_speed_error, topology_only=False): """ In-place segment simplification See `drp` and `compression` modules Args: eps (float): Distance threshold for the `drp` function max_dist_error (float): Max distance error, in meters ...
In-place segment simplification See `drp` and `compression` modules Args: eps (float): Distance threshold for the `drp` function max_dist_error (float): Max distance error, in meters max_speed_error (float): Max speed error, in km/h topology_only (bool, ...
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L134-L152
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.compute_metrics
def compute_metrics(self): """ Computes metrics for each point Returns: :obj:`Segment`: self """ for prev, point in pairwise(self.points): point.compute_metrics(prev) return self
python
def compute_metrics(self): """ Computes metrics for each point Returns: :obj:`Segment`: self """ for prev, point in pairwise(self.points): point.compute_metrics(prev) return self
Computes metrics for each point Returns: :obj:`Segment`: self
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L154-L162
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.infer_location
def infer_location( self, location_query, max_distance, google_key, foursquare_client_id, foursquare_client_secret, limit ): """In-place location inferring See infer_location function Args: Retu...
python
def infer_location( self, location_query, max_distance, google_key, foursquare_client_id, foursquare_client_secret, limit ): """In-place location inferring See infer_location function Args: Retu...
In-place location inferring See infer_location function Args: Returns: :obj:`Segment`: self
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L164-L201
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.infer_transportation_mode
def infer_transportation_mode(self, clf, min_time): """In-place transportation mode inferring See infer_transportation_mode function Args: Returns: :obj:`Segment`: self """ self.transportation_modes = speed_clustering(clf, self.points, min_time) retu...
python
def infer_transportation_mode(self, clf, min_time): """In-place transportation mode inferring See infer_transportation_mode function Args: Returns: :obj:`Segment`: self """ self.transportation_modes = speed_clustering(clf, self.points, min_time) retu...
In-place transportation mode inferring See infer_transportation_mode function Args: Returns: :obj:`Segment`: self
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L203-L213
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.merge_and_fit
def merge_and_fit(self, segment): """ Merges another segment with this one, ordering the points based on a distance heuristic Args: segment (:obj:`Segment`): Segment to merge with Returns: :obj:`Segment`: self """ self.points = sort_segment_po...
python
def merge_and_fit(self, segment): """ Merges another segment with this one, ordering the points based on a distance heuristic Args: segment (:obj:`Segment`): Segment to merge with Returns: :obj:`Segment`: self """ self.points = sort_segment_po...
Merges another segment with this one, ordering the points based on a distance heuristic Args: segment (:obj:`Segment`): Segment to merge with Returns: :obj:`Segment`: self
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L215-L225
ruipgil/TrackToTrip
tracktotrip/segment.py
Segment.closest_point_to
def closest_point_to(self, point, thr=20.0): """ Finds the closest point in the segment to a given point Args: point (:obj:`Point`) thr (float, optional): Distance threshold, in meters, to be considered the same point. Defaults to 20.0 Returns: ...
python
def closest_point_to(self, point, thr=20.0): """ Finds the closest point in the segment to a given point Args: point (:obj:`Point`) thr (float, optional): Distance threshold, in meters, to be considered the same point. Defaults to 20.0 Returns: ...
Finds the closest point in the segment to a given point Args: point (:obj:`Point`) thr (float, optional): Distance threshold, in meters, to be considered the same point. Defaults to 20.0 Returns: (int, Point): Index of the point. -1 if doesn't exist. ...
https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/segment.py#L227-L255