_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q3800
|
AsciiFormatter.format
|
train
|
def format(self, model: AssetAllocationModel, full: bool = False):
""" Returns the view-friendly output of the aa model """
self.full = full
# Header
output = f"Asset Allocation model, total: {model.currency} {model.total_amount:,.2f}\n"
# Column Headers
for column in self.columns:
name = column['name']
if not self.full and name == "loc.cur.":
# Skip local currency if not displaying stocks.
continue
width = column["width"]
output += f"{name:^{width}}"
output += "\n"
output += f"-------------------------------------------------------------------------------\n"
# Asset classes
view_model = ModelMapper(model).map_to_linear(self.full)
for row in view_model:
output += self.__format_row(row) + "\n"
return output
|
python
|
{
"resource": ""
}
|
q3801
|
AsciiFormatter.__format_row
|
train
|
def __format_row(self, row: AssetAllocationViewModel):
""" display-format one row
Formats one Asset Class record """
output = ""
index = 0
# Name
value = row.name
# Indent according to depth.
for _ in range(0, row.depth):
value = f" {value}"
output += self.append_text_column(value, index)
# Set Allocation
value = ""
index += 1
if row.set_allocation > 0:
value = f"{row.set_allocation:.2f}"
output += self.append_num_column(value, index)
# Current Allocation
value = ""
index += 1
if row.curr_allocation > Decimal(0):
value = f"{row.curr_allocation:.2f}"
output += self.append_num_column(value, index)
# Allocation difference, percentage
value = ""
index += 1
if row.alloc_diff_perc.copy_abs() > Decimal(0):
value = f"{row.alloc_diff_perc:.0f} %"
output += self.append_num_column(value, index)
# Allocated value
index += 1
value = ""
if row.set_value:
value = f"{row.set_value:,.0f}"
output += self.append_num_column(value, index)
# Current Value
index += 1
value = f"{row.curr_value:,.0f}"
output += self.append_num_column(value, index)
# Value in security's currency. Show only if displaying full model, with stocks.
index += 1
if self.full:
value = ""
if row.curr_value_own_currency:
value = f"({row.curr_value_own_currency:,.0f}"
value += f" {row.own_currency}"
value += ")"
output += self.append_num_column(value, index)
# https://en.wikipedia.org/wiki/ANSI_escape_code
# CSI="\x1B["
# red = 31, green = 32
# output += CSI+"31;40m" + "Colored Text" + CSI + "0m"
# Value diff
index += 1
value = ""
if row.diff_value:
value = f"{row.diff_value:,.0f}"
# Color the output
# value = f"{CSI};40m{value}{CSI};40m"
output += self.append_num_column(value, index)
return output
|
python
|
{
"resource": ""
}
|
q3802
|
AssetClassMapper.map_entity
|
train
|
def map_entity(self, entity: dal.AssetClass):
""" maps data from entity -> object """
obj = model.AssetClass()
obj.id = entity.id
obj.parent_id = entity.parentid
obj.name = entity.name
obj.allocation = entity.allocation
obj.sort_order = entity.sortorder
#entity.stock_links
#entity.diff_adjustment
if entity.parentid == None:
obj.depth = 0
return obj
|
python
|
{
"resource": ""
}
|
q3803
|
ModelMapper.map_to_linear
|
train
|
def map_to_linear(self, with_stocks: bool=False):
""" Maps the tree to a linear representation suitable for display """
result = []
for ac in self.model.classes:
rows = self.__get_ac_tree(ac, with_stocks)
result += rows
return result
|
python
|
{
"resource": ""
}
|
q3804
|
ModelMapper.__get_ac_tree
|
train
|
def __get_ac_tree(self, ac: model.AssetClass, with_stocks: bool):
""" formats the ac tree - entity with child elements """
output = []
output.append(self.__get_ac_row(ac))
for child in ac.classes:
output += self.__get_ac_tree(child, with_stocks)
if with_stocks:
for stock in ac.stocks:
row = None
if isinstance(stock, Stock):
row = self.__get_stock_row(stock, ac.depth + 1)
elif isinstance(stock, CashBalance):
row = self.__get_cash_row(stock, ac.depth + 1)
output.append(row)
return output
|
python
|
{
"resource": ""
}
|
q3805
|
ModelMapper.__get_ac_row
|
train
|
def __get_ac_row(self, ac: model.AssetClass) -> AssetAllocationViewModel:
""" Formats one Asset Class record """
view_model = AssetAllocationViewModel()
view_model.depth = ac.depth
# Name
view_model.name = ac.name
view_model.set_allocation = ac.allocation
view_model.curr_allocation = ac.curr_alloc
view_model.diff_allocation = ac.alloc_diff
view_model.alloc_diff_perc = ac.alloc_diff_perc
# value
view_model.curr_value = ac.curr_value
# expected value
view_model.set_value = ac.alloc_value
# diff
view_model.diff_value = ac.value_diff
return view_model
|
python
|
{
"resource": ""
}
|
q3806
|
AppAggregate.create_asset_class
|
train
|
def create_asset_class(self, item: AssetClass):
""" Inserts the record """
session = self.open_session()
session.add(item)
session.commit()
|
python
|
{
"resource": ""
}
|
q3807
|
AppAggregate.add_stock_to_class
|
train
|
def add_stock_to_class(self, assetclass_id: int, symbol: str):
""" Add a stock link to an asset class """
assert isinstance(symbol, str)
assert isinstance(assetclass_id, int)
item = AssetClassStock()
item.assetclassid = assetclass_id
item.symbol = symbol
session = self.open_session()
session.add(item)
self.save()
return item
|
python
|
{
"resource": ""
}
|
q3808
|
AppAggregate.delete
|
train
|
def delete(self, id: int):
""" Delete asset class """
assert isinstance(id, int)
self.open_session()
to_delete = self.get(id)
self.session.delete(to_delete)
self.save()
|
python
|
{
"resource": ""
}
|
q3809
|
AppAggregate.find_unallocated_holdings
|
train
|
def find_unallocated_holdings(self):
""" Identifies any holdings that are not included in asset allocation """
# Get linked securities
session = self.open_session()
linked_entities = session.query(AssetClassStock).all()
linked = []
# linked = map(lambda x: f"{x.symbol}", linked_entities)
for item in linked_entities:
linked.append(item.symbol)
# Get all securities with balance > 0.
from .stocks import StocksInfo
stocks = StocksInfo()
stocks.logger = self.logger
holdings = stocks.get_symbols_with_positive_balances()
# Find those which are not included in the stock links.
non_alloc = []
index = -1
for item in holdings:
try:
index = linked.index(item)
self.logger.debug(index)
except ValueError:
non_alloc.append(item)
return non_alloc
|
python
|
{
"resource": ""
}
|
q3810
|
AppAggregate.get
|
train
|
def get(self, id: int) -> AssetClass:
""" Loads Asset Class """
self.open_session()
item = self.session.query(AssetClass).filter(
AssetClass.id == id).first()
return item
|
python
|
{
"resource": ""
}
|
q3811
|
AppAggregate.open_session
|
train
|
def open_session(self):
""" Opens a db session and returns it """
from .dal import get_session
cfg = Config()
cfg.logger = self.logger
db_path = cfg.get(ConfigKeys.asset_allocation_database_path)
self.session = get_session(db_path)
return self.session
|
python
|
{
"resource": ""
}
|
q3812
|
AppAggregate.get_asset_allocation
|
train
|
def get_asset_allocation(self):
""" Creates and populates the Asset Allocation model. The main function of the app. """
# load from db
# TODO set the base currency
base_currency = "EUR"
loader = AssetAllocationLoader(base_currency=base_currency)
loader.logger = self.logger
model = loader.load_tree_from_db()
model.validate()
# securities
# read stock links
loader.load_stock_links()
# read stock quantities from GnuCash
loader.load_stock_quantity()
# Load cash balances
loader.load_cash_balances()
# loader.session
# read prices from Prices database
loader.load_stock_prices()
# recalculate stock values into base currency
loader.recalculate_stock_values_into_base()
# calculate
model.calculate_current_value()
model.calculate_set_values()
model.calculate_current_allocation()
# return the model for display
return model
|
python
|
{
"resource": ""
}
|
q3813
|
AppAggregate.validate_model
|
train
|
def validate_model(self):
""" Validate the model """
model: AssetAllocationModel = self.get_asset_allocation_model()
model.logger = self.logger
valid = model.validate()
if valid:
print(f"The model is valid. Congratulations")
else:
print(f"The model is invalid.")
|
python
|
{
"resource": ""
}
|
q3814
|
AppAggregate.export_symbols
|
train
|
def export_symbols(self):
""" Exports all used symbols """
session = self.open_session()
links = session.query(AssetClassStock).order_by(
AssetClassStock.symbol).all()
output = []
for link in links:
output.append(link.symbol + '\n')
# Save output to a text file.
with open("symbols.txt", mode='w') as file:
file.writelines(output)
print("Symbols exported to symbols.txt")
|
python
|
{
"resource": ""
}
|
q3815
|
Config.__read_config
|
train
|
def __read_config(self, file_path: str):
""" Read the config file """
if not os.path.exists(file_path):
raise FileNotFoundError("File path not found: %s", file_path)
# check if file exists
if not os.path.isfile(file_path):
log(ERROR, "file not found: %s", file_path)
raise FileNotFoundError("configuration file not found %s", file_path)
self.config.read(file_path)
|
python
|
{
"resource": ""
}
|
q3816
|
Config.__create_user_config
|
train
|
def __create_user_config(self):
""" Copy the config template into user's directory """
src_path = self.__get_config_template_path()
src = os.path.abspath(src_path)
if not os.path.exists(src):
log(ERROR, "Config template not found %s", src)
raise FileNotFoundError()
dst = os.path.abspath(self.get_config_path())
shutil.copyfile(src, dst)
if not os.path.exists(dst):
raise FileNotFoundError("Config file could not be copied to user dir!")
|
python
|
{
"resource": ""
}
|
q3817
|
set
|
train
|
def set(aadb, cur):
""" Sets the values in the config file """
cfg = Config()
edited = False
if aadb:
cfg.set(ConfigKeys.asset_allocation_database_path, aadb)
print(f"The database has been set to {aadb}.")
edited = True
if cur:
cfg.set(ConfigKeys.default_currency, cur)
edited = True
if edited:
print(f"Changes saved.")
else:
print(f"No changes were made.")
print(f"Use --help parameter for more information.")
|
python
|
{
"resource": ""
}
|
q3818
|
get
|
train
|
def get(aadb: str):
""" Retrieves a value from config """
if (aadb):
cfg = Config()
value = cfg.get(ConfigKeys.asset_allocation_database_path)
click.echo(value)
if not aadb:
click.echo("Use --help for more information.")
|
python
|
{
"resource": ""
}
|
q3819
|
_AssetBase.fullname
|
train
|
def fullname(self):
""" includes the full path with parent names """
prefix = ""
if self.parent:
if self.parent.fullname:
prefix = self.parent.fullname + ":"
else:
# Only the root does not have a parent. In that case we also don't need a name.
return ""
return prefix + self.name
|
python
|
{
"resource": ""
}
|
q3820
|
Stock.asset_class
|
train
|
def asset_class(self) -> str:
""" Returns the full asset class path for this stock """
result = self.parent.name if self.parent else ""
# Iterate to the top asset class and add names.
cursor = self.parent
while cursor:
result = cursor.name + ":" + result
cursor = cursor.parent
return result
|
python
|
{
"resource": ""
}
|
q3821
|
AssetClass.child_allocation
|
train
|
def child_allocation(self):
""" The sum of all child asset classes' allocations """
sum = Decimal(0)
if self.classes:
for child in self.classes:
sum += child.child_allocation
else:
# This is not a branch but a leaf. Return own allocation.
sum = self.allocation
return sum
|
python
|
{
"resource": ""
}
|
q3822
|
AssetAllocationModel.get_class_by_id
|
train
|
def get_class_by_id(self, ac_id: int) -> AssetClass:
""" Finds the asset class by id """
assert isinstance(ac_id, int)
# iterate recursively
for ac in self.asset_classes:
if ac.id == ac_id:
return ac
# if nothing returned so far.
return None
|
python
|
{
"resource": ""
}
|
q3823
|
AssetAllocationModel.get_cash_asset_class
|
train
|
def get_cash_asset_class(self) -> AssetClass:
""" Find the cash asset class by name. """
for ac in self.asset_classes:
if ac.name.lower() == "cash":
return ac
return None
|
python
|
{
"resource": ""
}
|
q3824
|
AssetAllocationModel.validate
|
train
|
def validate(self) -> bool:
""" Validate that the values match. Incomplete! """
# Asset class allocation should match the sum of children's allocations.
# Each group should be compared.
sum = Decimal(0)
# Go through each asset class, not just the top level.
for ac in self.asset_classes:
if ac.classes:
# get the sum of all the children's allocations
child_alloc_sum = ac.child_allocation
# compare to set allocation
if ac.allocation != child_alloc_sum:
message = f"The sum of child allocations {child_alloc_sum:.2f} invalid for {ac}!"
self.logger.warning(message)
print(message)
return False
# also make sure that the sum of 1st level children matches 100
for ac in self.classes:
sum += ac.allocation
if sum != Decimal(100):
message = f"The sum of all allocations ({sum:.2f}) does not equal 100!"
self.logger.warning(message)
print(message)
return False
return True
|
python
|
{
"resource": ""
}
|
q3825
|
AssetAllocationModel.calculate_set_values
|
train
|
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
|
{
"resource": ""
}
|
q3826
|
AssetAllocationModel.calculate_current_allocation
|
train
|
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
|
{
"resource": ""
}
|
q3827
|
AssetAllocationModel.calculate_current_value
|
train
|
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
|
{
"resource": ""
}
|
q3828
|
AssetAllocationModel.__calculate_current_value
|
train
|
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)
for stock in asset_class.stocks:
# recalculate into base currency!
stocks_sum += stock.value_in_base_currency
asset_class.curr_value = stocks_sum
if asset_class.classes:
# load totals for child classes
for child in asset_class.classes:
self.__calculate_current_value(child)
asset_class.curr_value += child.curr_value
|
python
|
{
"resource": ""
}
|
q3829
|
CurrencyConverter.load_currency
|
train
|
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 = PriceDbApplication()
# TODO use the base_currency parameter for the query #33
symbol = SecuritySymbol("CURRENCY", mnemonic)
self.rate = app.get_latest_price(symbol)
if not self.rate:
raise ValueError(f"No rate found for {mnemonic}!")
|
python
|
{
"resource": ""
}
|
q3830
|
show
|
train
|
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
else:
raise ValueError(f"Unknown formatter {format}")
# formatters can display stock information with --full
output = formatter.format(model, full=full)
print(output)
|
python
|
{
"resource": ""
}
|
q3831
|
AssetAllocationLoader.load_cash_balances
|
train
|
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 from all accounts under the root.
gc_db = self.config.get(ConfigKeys.gnucash_book_path)
with open_book(gc_db, open_if_lock=True) as book:
svc = AccountsAggregate(book)
root_account = svc.get_by_fullname(cash_root_name)
acct_svc = AccountAggregate(book, root_account)
cash_balances = acct_svc.load_cash_balances_with_children(cash_root_name)
# Treat each sum per currency as a Stock, for display in full mode.
self.__store_cash_balances_per_currency(cash_balances)
|
python
|
{
"resource": ""
}
|
q3832
|
AssetAllocationLoader.__store_cash_balances_per_currency
|
train
|
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
quantity = cash_balances[cur_symbol]["total"]
item.value = Decimal(quantity)
item.currency = cur_symbol
# self.logger.debug(f"adding {item}")
cash.stocks.append(item)
self.model.stocks.append(item)
|
python
|
{
"resource": ""
}
|
q3833
|
AssetAllocationLoader.load_tree_from_db
|
train
|
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 = self.__get_session()
first_level = (
db.query(dal.AssetClass)
.filter(dal.AssetClass.parentid == None)
.order_by(dal.AssetClass.sortorder)
.all()
)
# create tree
for entity in first_level:
ac = self.__map_entity(entity)
self.model.classes.append(ac)
# Add to index
self.model.asset_classes.append(ac)
# append child classes recursively
self.__load_child_classes(ac)
return self.model
|
python
|
{
"resource": ""
}
|
q3834
|
AssetAllocationLoader.load_stock_links
|
train
|
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)
# find parent classes by id and assign children
parent: AssetClass = self.model.get_class_by_id(entity.assetclassid)
if parent:
# Assign to parent.
parent.stocks.append(stock)
# Add to index for easy reference
self.model.stocks.append(stock)
|
python
|
{
"resource": ""
}
|
q3835
|
AssetAllocationLoader.load_stock_quantity
|
train
|
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
|
{
"resource": ""
}
|
q3836
|
AssetAllocationLoader.load_stock_prices
|
train
|
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_price(symbol)
if not price:
# Use a dummy price of 1, effectively keeping the original amount.
price = PriceModel()
price.currency = self.config.get(ConfigKeys.default_currency)
price.value = Decimal(1)
item.price = price.value
if isinstance(item, Stock):
item.currency = price.currency
# Do not set currency for Cash balance records.
info.close_databases()
|
python
|
{
"resource": ""
}
|
q3837
|
AssetAllocationLoader.recalculate_stock_values_into_base
|
train
|
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.stocks:
if stock.currency != self.base_currency:
# Recalculate into base currency
conv.load_currency(stock.currency)
assert isinstance(stock.value, Decimal)
val_base = stock.value * conv.rate.value
else:
# Already in base currency.
val_base = stock.value
stock.value_in_base_currency = val_base
|
python
|
{
"resource": ""
}
|
q3838
|
AssetAllocationLoader.__map_entity
|
train
|
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
|
{
"resource": ""
}
|
q3839
|
AssetAllocationLoader.__get_session
|
train
|
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
|
{
"resource": ""
}
|
q3840
|
AssetAllocationLoader.__load_asset_class
|
train
|
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
|
{
"resource": ""
}
|
q3841
|
get_session
|
train
|
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)
# create metadata (?)
Base.metadata.create_all(engine)
# create session
Session = sessionmaker(bind=engine)
session = Session()
return session
|
python
|
{
"resource": ""
}
|
q3842
|
add
|
train
|
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
|
{
"resource": ""
}
|
q3843
|
edit
|
train
|
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."
# TODO check if parent exists?
item.parentid = parent
saved = True
# click.echo(f"parent set to {parent}")
if alloc:
assert alloc != Decimal(0)
item.allocation = alloc
saved = True
app.save()
if saved:
click.echo("Data saved.")
else:
click.echo("No data modified. Use --help to see possible parameters.")
|
python
|
{
"resource": ""
}
|
q3844
|
my_list
|
train
|
def my_list():
""" Lists all asset classes """
session = AppAggregate().open_session()
classes = session.query(AssetClass).all()
for item in classes:
print(item)
|
python
|
{
"resource": ""
}
|
q3845
|
tree
|
train
|
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
print_row("id", "asset class", "allocation", "level")
print(f"-------------------------------")
for ac in root:
print_item_with_children(ac, classes, 0)
|
python
|
{
"resource": ""
}
|
q3846
|
print_item_with_children
|
train
|
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
|
{
"resource": ""
}
|
q3847
|
print_children_recursively
|
train
|
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 = " " * level * 2
id_col = f"{indent} {child.id}"
print_row(id_col, child.name, f"{child.allocation:,.2f}", level)
# Process children.
print_children_recursively(all_items, child, level+1)
|
python
|
{
"resource": ""
}
|
q3848
|
print_row
|
train
|
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
|
{
"resource": ""
}
|
q3849
|
render_html
|
train
|
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
|
{
"resource": ""
}
|
q3850
|
Parser.add_simple_formatter
|
train
|
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):
fmt = {}
if options:
fmt.update(options)
fmt.update({'value': value})
return format_string % fmt
self.add_formatter(tag_name, _render, **kwargs)
|
python
|
{
"resource": ""
}
|
q3851
|
Parser._newline_tokenize
|
train
|
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 = []
for num, part in enumerate(parts):
if part:
tokens.append((self.TOKEN_DATA, None, None, part))
if num < (len(parts) - 1):
tokens.append((self.TOKEN_NEWLINE, None, None, '\n'))
return tokens
|
python
|
{
"resource": ""
}
|
q3852
|
Parser._link_replace
|
train
|
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 passed context like a standard format function.
"""
url = match.group(0)
if self.linker:
if self.linker_takes_context:
return self.linker(url, context)
else:
return self.linker(url)
else:
href = url
if '://' not in href:
href = 'http://' + href
# Escape quotes to avoid XSS, let the browser escape the rest.
return self.url_template.format(href=href.replace('"', '%22'), text=url)
|
python
|
{
"resource": ""
}
|
q3853
|
Parser._transform
|
train
|
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 self.replace_links and replace_links:
# If we're replacing links in the text (i.e. not those in [url] tags) then we need to be
# careful to pull them out before doing any escaping or cosmetic replacement.
pos = 0
while True:
match = _url_re.search(data, pos)
if not match:
break
# Replace any link with a token that we can substitute back in after replacements.
token = '{{ bbcode-link-%s }}' % len(url_matches)
url_matches[token] = self._link_replace(match, **context)
start, end = match.span()
data = data[:start] + token + data[end:]
# To be perfectly accurate, this should probably be len(data[:start] + token), but
# start will work, because the token itself won't match as a URL.
pos = start
if escape_html:
data = self._replace(data, self.REPLACE_ESCAPE)
if replace_cosmetic:
data = self._replace(data, self.REPLACE_COSMETIC)
# Now put the replaced links back in the text.
for token, replacement in url_matches.items():
data = data.replace(token, replacement)
if transform_newlines:
data = data.replace('\n', '\r')
return data
|
python
|
{
"resource": ""
}
|
q3854
|
Parser.format
|
train
|
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.copy()
full_context.update(context)
return self._format_tokens(tokens, None, **full_context).replace('\r', self.newline)
|
python
|
{
"resource": ""
}
|
q3855
|
Parser.strip
|
train
|
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:
text.append(token_text)
elif token_type == self.TOKEN_NEWLINE and not strip_newlines:
text.append(token_text)
return ''.join(text)
|
python
|
{
"resource": ""
}
|
q3856
|
mode_in_range
|
train
|
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
|
{
"resource": ""
}
|
q3857
|
PeriodicModeler.score_frequency_grid
|
train
|
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 grid freq = f0 + df * arange(N)
Note that these are frequencies, not angular frequencies.
Returns
-------
score : ndarray
the length-N array giving the score at each frequency
"""
return self._score_frequency_grid(f0, df, N)
|
python
|
{
"resource": ""
}
|
q3858
|
PeriodicModeler.periodogram_auto
|
train
|
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 window function,
the model may be sensitive to periodicity at higher frequencies than
this function returns!
The final number of frequencies will be
Nf = oversampling * nyquist_factor * len(t) / 2
Parameters
----------
oversampling : float
the number of samples per approximate peak width
nyquist_factor : float
the highest frequency, in units of the nyquist frequency for points
spread uniformly through the data range.
Returns
-------
period : ndarray
the grid of periods
power : ndarray
the power at each frequency
"""
N = len(self.t)
T = np.max(self.t) - np.min(self.t)
df = 1. / T / oversampling
f0 = df
Nf = int(0.5 * oversampling * nyquist_factor * N)
freq = f0 + df * np.arange(Nf)
return 1. / freq, self._score_frequency_grid(f0, df, Nf)
|
python
|
{
"resource": ""
}
|
q3859
|
PeriodicModeler.score
|
train
|
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 of normalized powers (between 0 and 1) for each period.
Shape of scores matches the shape of the provided periods.
"""
periods = np.asarray(periods)
return self._score(periods.ravel()).reshape(periods.shape)
|
python
|
{
"resource": ""
}
|
q3860
|
PeriodicModeler.best_period
|
train
|
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
|
{
"resource": ""
}
|
q3861
|
PeriodicModeler.find_best_periods
|
train
|
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
|
{
"resource": ""
}
|
q3862
|
LeastSquaresMixin._construct_X_M
|
train
|
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]
if self.regularize_by_trace:
diag += diag.sum() * np.asarray(self.regularization)
else:
diag += np.asarray(self.regularization)
return X, M
|
python
|
{
"resource": ""
}
|
q3863
|
LombScargle._construct_X
|
train
|
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))]
else:
offsets = []
cols = sum(([np.sin((i + 1) * omega * t),
np.cos((i + 1) * omega * t)]
for i in range(self.Nterms)), offsets)
if weighted:
return np.transpose(np.vstack(cols) / dy)
else:
return np.transpose(np.vstack(cols))
|
python
|
{
"resource": ""
}
|
q3864
|
BaseTemplateModeler._interpolated_template
|
train
|
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, we need to add ~5 points to make sure
# the spline & derivatives wrap appropriately
phase = np.concatenate([phase[-5:] - 1, phase, phase[:5] + 1])
y = np.concatenate([y[-5:], y, y[:5]])
# Univariate spline allows for derivatives; use this!
return UnivariateSpline(phase, y, s=0, k=5)
|
python
|
{
"resource": ""
}
|
q3865
|
BaseTemplateModeler._eval_templates
|
train
|
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)]
return theta_best, chi2
|
python
|
{
"resource": ""
}
|
q3866
|
BaseTemplateModeler._model
|
train
|
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
|
{
"resource": ""
}
|
q3867
|
BaseTemplateModeler._chi2
|
train
|
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
model = theta[0] + theta[1] * template(phase)
chi2 = (((model - self.y) / self.dy) ** 2).sum()
if return_gradient:
grad = 2 * (model - self.y) / self.dy ** 2
gradient = np.array([np.sum(grad),
np.sum(grad * template(phase)),
-np.sum(grad * theta[1]
* template.derivative(1)(phase))])
return chi2, gradient
else:
return chi2
|
python
|
{
"resource": ""
}
|
q3868
|
BaseTemplateModeler._optimize
|
train
|
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, None)],
args=(period, tmpid, use_gradient))
return result.x
|
python
|
{
"resource": ""
}
|
q3869
|
factorial
|
train
|
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
|
{
"resource": ""
}
|
q3870
|
RRLyraeGenerated.observed
|
train
|
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
Returns
-------
t, mag, dmag : ndarrays
The times, magnitudes, and magnitude errors for the specified band.
"""
if band not in 'ugriz':
raise ValueError("band='{0}' not recognized".format(band))
i = 'ugriz'.find(band)
t, y, dy = self.lcdata.get_lightcurve(self.lcid, return_1d=False)
if corrected:
ext = self.obsmeta['rExt'] * self.ext_correction[band]
else:
ext = 0
return t[:, i], y[:, i] - ext, dy[:, i]
|
python
|
{
"resource": ""
}
|
q3871
|
RRLyraeGenerated.generated
|
train
|
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 : float or array_like
gaussian error in observations
corrected : bool (optional)
If true, correct for extinction
Returns
-------
mag : ndarray
magnitudes at the specified times under the generated model.
"""
t = np.asarray(t)
num = self.meta[band + 'T']
mu = self.meta[band + '0']
amp = self.meta[band + 'A']
t0 = self.meta[band + 'E']
# if there are nans or infinities, mask them
bad_vals = np.isnan(t) | np.isinf(t)
t[bad_vals] = t0
if corrected:
ext = 0
else:
ext = self.obsmeta['rExt'] * self.ext_correction[band]
func = self._template_func(num, band, mu + ext, amp)
mag = func(((t - t0) / self.period) % 1)
mag[bad_vals] = np.nan
if err is not None:
mag += self.rng.normal(0, err, t.shape)
return mag
|
python
|
{
"resource": ""
}
|
q3872
|
fetch_rrlyrae
|
train
|
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 contains pointers to the RR Lyrae data.
Other Parameters
----------------
data_home : str (optional)
Specify the local cache directory for the dataset. If not used, it
will default to the ``astroML`` default location.
url : str (optional)
Specify the URL of the datasets. Defaults to webpage associated with
Sesar 2010.
force_download : bool (optional)
If true, then force re-downloading data even if it is already cached
locally. Default is False.
Examples
--------
>>> rrlyrae = fetch_rrlyrae()
>>> rrlyrae.ids[:5]
[1013184, 1019544, 1027882, 1052471, 1056152]
>>> lcid = rrlyrae.ids[0]
>>> t, mag, dmag, bands = rrlyrae.get_lightcurve(lcid)
>>> t[:4]
array([ 51081.347856, 51081.349522, 51081.346189, 51081.347022])
>>> mag[:4]
array([ 18.702, 17.553, 17.236, 17.124])
>>> dmag[:4]
array([ 0.021, 0.005, 0.005, 0.006])
>>> list(bands[:4])
['u', 'g', 'r', 'i']
"""
if partial:
return PartialRRLyraeLC('table1.tar.gz',
cache_kwargs=kwargs)
else:
return RRLyraeLC('table1.tar.gz',
cache_kwargs=kwargs)
|
python
|
{
"resource": ""
}
|
q3873
|
fetch_rrlyrae_lc_params
|
train
|
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'),
('uA', 'f'), ('u0', 'f'), ('uE', 'f'), ('uT', 'f'),
('gA', 'f'), ('g0', 'f'), ('gE', 'f'), ('gT', 'f'),
('rA', 'f'), ('r0', 'f'), ('rE', 'f'), ('rT', 'f'),
('iA', 'f'), ('i0', 'f'), ('iE', 'f'), ('iT', 'f'),
('zA', 'f'), ('z0', 'f'), ('zE', 'f'), ('zT', 'f')]
return np.loadtxt(save_loc, dtype=dtype)
|
python
|
{
"resource": ""
}
|
q3874
|
fetch_rrlyrae_fitdata
|
train
|
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', 'f'),
('d', 'f'), ('RGC', 'f'),
('u', 'f'), ('g', 'f'), ('r', 'f'),
('i', 'f'), ('z', 'f'), ('V', 'f'),
('ugmin', 'f'), ('ugmin_err', 'f'),
('grmin', 'f'), ('grmin_err', 'f')]
return np.loadtxt(save_loc, dtype=dtype)
|
python
|
{
"resource": ""
}
|
q3875
|
RRLyraeLC.get_lightcurve
|
train
|
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 arrays of (t, y, dy, filts) or
2D arrays of (t, y, dy) where each column is a filter.
Returns
-------
t, y, dy : np.ndarrays (if return_1d == False)
Times, magnitudes, and magnitude errors.
The shape of each array is [Nobs, 5], where the columns refer
to [u,g,r,i,z] bands. Non-observations are indicated by NaN.
t, y, dy, filts : np.ndarrays (if return_1d == True)
Times, magnitudes, magnitude errors, and filters
The shape of each array is [Nobs], and non-observations are
filtered out.
"""
filename = '{0}/{1}.dat'.format(self.dirname, star_id)
try:
data = np.loadtxt(self.data.extractfile(filename))
except KeyError:
raise ValueError("invalid star id: {0}".format(star_id))
RA = data[:, 0]
DEC = data[:, 1]
t = data[:, 2::3]
y = data[:, 3::3]
dy = data[:, 4::3]
nans = (y == -99.99)
t[nans] = np.nan
y[nans] = np.nan
dy[nans] = np.nan
if return_1d:
t, y, dy, filts = np.broadcast_arrays(t, y, dy,
['u', 'g', 'r', 'i', 'z'])
good = ~np.isnan(t)
return t[good], y[good], dy[good], filts[good]
else:
return t, y, dy
|
python
|
{
"resource": ""
}
|
q3876
|
RRLyraeLC.get_metadata
|
train
|
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:
raise ValueError("invalid lcid: {0}".format(lcid))
return self._metadata[i[0]]
|
python
|
{
"resource": ""
}
|
q3877
|
RRLyraeLC.get_obsmeta
|
train
|
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 ValueError("invalid lcid: {0}".format(lcid))
return self._obsdata[i[0]]
|
python
|
{
"resource": ""
}
|
q3878
|
RRLyraeTemplates.get_template
|
train
|
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 normalized magnitudes
"""
try:
data = np.loadtxt(self.data.extractfile(template_id + '.dat'))
except KeyError:
raise ValueError("invalid star id: {0}".format(template_id))
return data[:, 0], data[:, 1]
|
python
|
{
"resource": ""
}
|
q3879
|
TCXParser.hr_avg
|
train
|
def hr_avg(self):
"""Average heart rate of the workout"""
hr_data = self.hr_values()
return int(sum(hr_data) / len(hr_data))
|
python
|
{
"resource": ""
}
|
q3880
|
TCXParser.ascent
|
train
|
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
return total_ascent
|
python
|
{
"resource": ""
}
|
q3881
|
TCXParser.descent
|
train
|
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)
return total_descent
|
python
|
{
"resource": ""
}
|
q3882
|
keywords_special_characters
|
train
|
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):
raise ValidationError(MESSAGE_KEYWORD_SPECIAL_CHARS)
|
python
|
{
"resource": ""
}
|
q3883
|
image_format
|
train
|
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:
raise ValidationError(MESSAGE_INVALID_IMAGE_FORMAT)
|
python
|
{
"resource": ""
}
|
q3884
|
no_company_with_insufficient_companies_house_data
|
train
|
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 prefix, name in company_types_with_insufficient_companies_house_data:
if value.upper().startswith(prefix):
raise ValidationError(
MESSAGE_INSUFFICIENT_DATA, params={'name': name}
)
|
python
|
{
"resource": ""
}
|
q3885
|
remove_liers
|
train
|
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):
prv = points[i-1]
crr = points[i]
nxt = points[i+1]
if prv.time <= crr.time and crr.time <= nxt.time:
result.append(crr)
result.append(points[-1])
return result
|
python
|
{
"resource": ""
}
|
q3886
|
Segment.bounds
|
train
|
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:`float`: Bounds of the (sub)segment, such that
(min_lat, min_lon, max_lat, max_lon)
"""
points = self.points[lower_index:upper_index]
min_lat = float("inf")
min_lon = float("inf")
max_lat = -float("inf")
max_lon = -float("inf")
for point in points:
min_lat = min(min_lat, point.lat)
min_lon = min(min_lon, point.lon)
max_lat = max(max_lat, point.lat)
max_lon = max(max_lon, point.lon)
return (min_lat - thr, min_lon - thr, max_lat + thr, max_lon + thr)
|
python
|
{
"resource": ""
}
|
q3887
|
Segment.smooth
|
train
|
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:
:obj:`Segment`
"""
if strategy is INVERSE_STRATEGY:
self.points = with_inverse(self.points, noise)
elif strategy is EXTRAPOLATE_STRATEGY:
self.points = with_extrapolation(self.points, noise, 30)
elif strategy is NO_STRATEGY:
self.points = with_no_strategy(self.points, noise)
return self
|
python
|
{
"resource": ""
}
|
q3888
|
Segment.simplify
|
train
|
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
max_speed_error (float): Max speed error, in km/h
topology_only (bool, optional): True to only keep topology, not considering
times when simplifying. Defaults to False.
Returns:
:obj:`Segment`
"""
if topology_only:
self.points = drp(self.points, eps)
else:
self.points = spt(self.points, max_dist_error, max_speed_error)
return self
|
python
|
{
"resource": ""
}
|
q3889
|
Segment.compute_metrics
|
train
|
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
|
{
"resource": ""
}
|
q3890
|
Segment.infer_location
|
train
|
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:
Returns:
:obj:`Segment`: self
"""
self.location_from = infer_location(
self.points[0],
location_query,
max_distance,
google_key,
foursquare_client_id,
foursquare_client_secret,
limit
)
self.location_to = infer_location(
self.points[-1],
location_query,
max_distance,
google_key,
foursquare_client_id,
foursquare_client_secret,
limit
)
return self
|
python
|
{
"resource": ""
}
|
q3891
|
Segment.infer_transportation_mode
|
train
|
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)
return self
|
python
|
{
"resource": ""
}
|
q3892
|
Segment.merge_and_fit
|
train
|
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_points(self.points, segment.points)
return self
|
python
|
{
"resource": ""
}
|
q3893
|
Segment.closest_point_to
|
train
|
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:
(int, Point): Index of the point. -1 if doesn't exist. A point is given if it's along the segment
"""
i = 0
point_arr = point.gen2arr()
def closest_in_line(pointA, pointB):
temp = closest_point(pointA.gen2arr(), pointB.gen2arr(), point_arr)
return Point(temp[1], temp[0], None)
for (p_a, p_b) in pairwise(self.points):
candidate = closest_in_line(p_a, p_b)
if candidate.distance(point) <= thr:
if p_a.distance(point) <= thr:
return i, p_a
elif p_b.distance(point) <= thr:
return i + 1, p_b
else:
return i, candidate
i = i + 1
return -1, None
|
python
|
{
"resource": ""
}
|
q3894
|
Segment.slice
|
train
|
def slice(self, start, end):
""" Creates a copy of the current segment between indexes. If end > start,
points are reverted
Args:
start (int): Start index
end (int): End index
Returns:
:obj:`Segment`
"""
reverse = False
if start > end:
temp = start
start = end
end = temp
reverse = True
seg = self.copy()
seg.points = seg.points[start:end+1]
if reverse:
seg.points = list(reversed(seg.points))
return seg
|
python
|
{
"resource": ""
}
|
q3895
|
Segment.to_json
|
train
|
def to_json(self):
""" Converts segment to a JSON serializable format
Returns:
:obj:`dict`
"""
points = [point.to_json() for point in self.points]
return {
'points': points,
'transportationModes': self.transportation_modes,
'locationFrom': self.location_from.to_json() if self.location_from != None else None,
'locationTo': self.location_to.to_json() if self.location_to != None else None
}
|
python
|
{
"resource": ""
}
|
q3896
|
Segment.from_gpx
|
train
|
def from_gpx(gpx_segment):
""" Creates a segment from a GPX format.
No preprocessing is done.
Arguments:
gpx_segment (:obj:`gpxpy.GPXTrackSegment`)
Return:
:obj:`Segment`
"""
points = []
for point in gpx_segment.points:
points.append(Point.from_gpx(point))
return Segment(points)
|
python
|
{
"resource": ""
}
|
q3897
|
Segment.from_json
|
train
|
def from_json(json):
""" Creates a segment from a JSON file.
No preprocessing is done.
Arguments:
json (:obj:`dict`): JSON representation. See to_json.
Return:
:obj:`Segment`
"""
points = []
for point in json['points']:
points.append(Point.from_json(point))
return Segment(points)
|
python
|
{
"resource": ""
}
|
q3898
|
extrapolate_points
|
train
|
def extrapolate_points(points, n_points):
""" Extrapolate a number of points, based on the first ones
Args:
points (:obj:`list` of :obj:`Point`)
n_points (int): number of points to extrapolate
Returns:
:obj:`list` of :obj:`Point`
"""
points = points[:n_points]
lat = []
lon = []
last = None
for point in points:
if last is not None:
lat.append(last.lat-point.lat)
lon.append(last.lon-point.lon)
last = point
dts = np.mean([p.dt for p in points])
lons = np.mean(lon)
lats = np.mean(lat)
gen_sample = []
last = points[0]
for _ in range(n_points):
point = Point(last.lat+lats, last.lon+lons, None)
point.dt = dts
# point.compute_metrics(last)
gen_sample.append(point)
last = point
return gen_sample
|
python
|
{
"resource": ""
}
|
q3899
|
with_extrapolation
|
train
|
def with_extrapolation(points, noise, n_points):
""" Smooths a set of points, but it extrapolates some points at the beginning
Args:
points (:obj:`list` of :obj:`Point`)
noise (float): Expected noise, the higher it is the more the path will
be smoothed.
Returns:
:obj:`list` of :obj:`Point`
"""
n_points = 10
return kalman_filter(extrapolate_points(points, n_points) + points, noise)[n_points:]
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.