_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 s... | 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}"... | 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:
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:
... | 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
... | 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... | 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}", ... | 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.logg... | 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 mode... | 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 ... | 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_pat... | 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:
cfg.set(ConfigKeys.default_currenc... | 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.
... | 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
c... | 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.
... | 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 sel... | 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)
f... | 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 = PriceDbApplicati... | 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 ... | 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
... | 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 = s... | 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... | 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... | 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.s... | 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)
# c... | 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."
... | 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
... | 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 = ... | 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):
... | 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 = []
... | 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 p... | 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 sel... | 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... | 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 = (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 gri... | 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 win... | 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 ... | 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]
... | 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))]
... | 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, ... | 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)... | 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
mo... | 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... | 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
Return... | 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 ... | 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 conta... | 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'),
... | 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', ... | 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 a... | 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:
... | 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 Va... | 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 normaliz... | 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
r... | 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)
... | 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... | 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:
... | 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 p... | 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):
... | 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:`fl... | 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:
... | 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
... | 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:
Retu... | 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)
retu... | 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_po... | 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:
... | 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... | 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,
'locati... | 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... | 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... | 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 = []
... | 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:`li... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.