_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| 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
|
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,
|
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
|
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:
|
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):
|
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
|
python
|
{
"resource": ""
}
|
q3806
|
AppAggregate.create_asset_class
|
train
|
def create_asset_class(self, item: AssetClass):
""" Inserts the record """
|
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)
|
python
|
{
"resource": ""
}
|
q3808
|
AppAggregate.delete
|
train
|
def delete(self, id: int):
""" Delete asset class """
assert isinstance(id, int)
self.open_session()
|
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()
|
python
|
{
"resource": ""
}
|
q3810
|
AppAggregate.get
|
train
|
def get(self, id: int) -> AssetClass:
""" Loads Asset Class """
self.open_session()
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
|
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()
|
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:
|
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
|
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):
|
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()
|
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:
|
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)
|
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:
|
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
|
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
|
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:
|
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:
|
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
#
|
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:
|
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:
|
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:
|
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
|
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:
|
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
|
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.
|
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:
|
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()
)
|
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
|
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:
|
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()
|
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)
|
python
|
{
"resource": ""
}
|
q3838
|
AssetAllocationLoader.__map_entity
|
train
|
def __map_entity(self, entity: dal.AssetClass) -> AssetClass:
""" maps the entity onto
|
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)
|
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()
|
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:///"
|
python
|
{
"resource": ""
}
|
q3842
|
add
|
train
|
def add(name):
""" Add new Asset Class """
item = AssetClass()
item.name = name
app = AppAggregate()
|
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
|
python
|
{
"resource": ""
}
|
q3844
|
my_list
|
train
|
def my_list():
""" Lists all asset classes """
session = AppAggregate().open_session()
|
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)
#
|
python
|
{
"resource": ""
}
|
q3846
|
print_item_with_children
|
train
|
def print_item_with_children(ac, classes, level):
""" Print the given item and all children
|
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 =
|
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
|
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.
"""
|
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
|
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:
|
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)
|
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:]
|
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 =
|
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:
|
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
|
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)
|
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
|
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.
|
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:
|
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"""
|
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
|
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),
|
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
|
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)]
|
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]
|
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),
|
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),
|
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):
|
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))
|
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
|
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
|
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',
|
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)
|
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
|
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()
|
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:
|
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:
|
python
|
{
"resource": ""
}
|
q3879
|
TCXParser.hr_avg
|
train
|
def hr_avg(self):
"""Average heart rate of the workout"""
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):
|
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):
|
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
"""
|
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
|
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
|
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 =
|
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 =
|
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
|
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.
|
python
|
{
"resource": ""
}
|
q3889
|
Segment.compute_metrics
|
train
|
def compute_metrics(self):
""" Computes metrics for each point
Returns:
:obj:`Segment`: 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,
|
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
|
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:
|
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)
|
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
|
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,
|
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`
"""
|
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`
"""
|
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])
|
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.
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.