_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q272300 | list_dates_between | test | def list_dates_between(first_date, last_date):
"""Returns all dates from first to last included."""
return [first_date + timedelta(days=n)
for n in range(1 + (last_date - first_date).days)] | python | {
"resource": ""
} |
q272301 | parse_date | test | def parse_date(s):
"""Fast %Y-%m-%d parsing."""
try:
return datetime.date(int(s[:4]), int(s[5:7]), int(s[8:10]))
except ValueError: # other accepted format used in one-day data set
return datetime.datetime.strptime(s, '%d %B %Y').date() | python | {
"resource": ""
} |
q272302 | CurrencyConverter.load_file | test | def load_file(self, currency_file):
"""To be subclassed if alternate methods of loading data.
"""
if currency_file.startswith(('http://', 'https://')):
content = urlopen(currency_file).read()
else:
with open(currency_file, 'rb') as f:
content = f.r... | python | {
"resource": ""
} |
q272303 | CurrencyConverter._set_missing_to_none | test | def _set_missing_to_none(self, currency):
"""Fill missing rates of a currency with the closest available ones."""
rates = self._rates[currency]
first_date, last_date = self.bounds[currency]
for date in list_dates_between(first_date, last_date):
if date not in rates:
... | python | {
"resource": ""
} |
q272304 | CurrencyConverter._compute_missing_rates | test | def _compute_missing_rates(self, currency):
"""Fill missing rates of a currency.
This is done by linear interpolation of the two closest available rates.
:param str currency: The currency to fill missing rates for.
"""
rates = self._rates[currency]
# tmp will store the... | python | {
"resource": ""
} |
q272305 | CurrencyConverter._get_rate | test | def _get_rate(self, currency, date):
"""Get a rate for a given currency and date.
:type date: datetime.date
>>> from datetime import date
>>> c = CurrencyConverter()
>>> c._get_rate('USD', date=date(2014, 3, 28))
1.375...
>>> c._get_rate('BGN', date=date(2010, 1... | python | {
"resource": ""
} |
q272306 | CurrencyConverter.convert | test | def convert(self, amount, currency, new_currency='EUR', date=None):
"""Convert amount from a currency to another one.
:param float amount: The amount of `currency` to convert.
:param str currency: The currency to convert from.
:param str new_currency: The currency to convert to.
... | python | {
"resource": ""
} |
q272307 | grouper | test | def grouper(iterable, n, fillvalue=None):
"""Group iterable by n elements.
>>> for t in grouper('abcdefg', 3, fillvalue='x'):
... print(''.join(t))
abc
def
gxx
"""
return list(zip_longest(*[iter(iterable)] * n, fillvalue=fillvalue)) | python | {
"resource": ""
} |
q272308 | animate | test | def animate(frames, interval, name, iterations=2):
"""Animate given frame for set number of iterations.
Parameters
----------
frames : list
Frames for animating
interval : float
Interval between two frames
name : str
Name of animation
iterations : int, optional
... | python | {
"resource": ""
} |
q272309 | DAF.read_record | test | def read_record(self, n):
"""Return record `n` as 1,024 bytes; records are indexed from 1."""
self.file.seek(n * K - K)
return self.file.read(K) | python | {
"resource": ""
} |
q272310 | DAF.write_record | test | def write_record(self, n, data):
"""Write `data` to file record `n`; records are indexed from 1."""
self.file.seek(n * K - K)
return self.file.write(data) | python | {
"resource": ""
} |
q272311 | DAF.map_words | test | def map_words(self, start, end):
"""Return a memory-map of the elements `start` through `end`.
The memory map will offer the 8-byte double-precision floats
("elements") in the file from index `start` through to the index
`end`, inclusive, both counting the first float as element 1.
... | python | {
"resource": ""
} |
q272312 | DAF.comments | test | def comments(self):
"""Return the text inside the comment area of the file."""
record_numbers = range(2, self.fward)
if not record_numbers:
return ''
data = b''.join(self.read_record(n)[0:1000] for n in record_numbers)
try:
return data[:data.find(b'\4')].d... | python | {
"resource": ""
} |
q272313 | DAF.add_array | test | def add_array(self, name, values, array):
"""Add a new array to the DAF file.
The summary will be initialized with the `name` and `values`,
and will have its start word and end word fields set to point to
where the `array` of floats has been appended to the file.
"""
f ... | python | {
"resource": ""
} |
q272314 | SPK.close | test | def close(self):
"""Close this SPK file."""
self.daf.file.close()
for segment in self.segments:
if hasattr(segment, '_data'):
del segment._data
self.daf._array = None
self.daf._map = None | python | {
"resource": ""
} |
q272315 | Segment.compute | test | def compute(self, tdb, tdb2=0.0):
"""Compute the component values for the time `tdb` plus `tdb2`."""
for position in self.generate(tdb, tdb2):
return position | python | {
"resource": ""
} |
q272316 | BinaryPCK.close | test | def close(self):
"""Close this file."""
self.daf.file.close()
for segment in self.segments:
if hasattr(segment, '_data'):
del segment._data | python | {
"resource": ""
} |
q272317 | Segment._load | test | def _load(self):
"""Map the coefficients into memory using a NumPy array.
"""
if self.data_type == 2:
component_count = 3
else:
raise ValueError('only binary PCK data type 2 is supported')
init, intlen, rsize, n = self.daf.read_array(self.end_i - 3, self... | python | {
"resource": ""
} |
q272318 | Segment.compute | test | def compute(self, tdb, tdb2, derivative=True):
"""Generate angles and derivatives for time `tdb` plus `tdb2`.
If ``derivative`` is true, return a tuple containing both the
angle and its derivative; otherwise simply return the angles.
"""
scalar = not getattr(tdb, 'shape', 0) an... | python | {
"resource": ""
} |
q272319 | LoggingVisitor.visit_Call | test | def visit_Call(self, node):
"""
Visit a function call.
We expect every logging statement and string format to be a function call.
"""
# CASE 1: We're in a logging statement
if self.within_logging_statement():
if self.within_logging_argument() and self.is_for... | python | {
"resource": ""
} |
q272320 | LoggingVisitor.visit_BinOp | test | def visit_BinOp(self, node):
"""
Process binary operations while processing the first logging argument.
"""
if self.within_logging_statement() and self.within_logging_argument():
# handle percent format
if isinstance(node.op, Mod):
self.violations... | python | {
"resource": ""
} |
q272321 | LoggingVisitor.visit_Dict | test | def visit_Dict(self, node):
"""
Process dict arguments.
"""
if self.should_check_whitelist(node):
for key in node.keys:
if key.s in self.whitelist or key.s.startswith("debug_"):
continue
self.violations.append((self.current... | python | {
"resource": ""
} |
q272322 | LoggingVisitor.visit_JoinedStr | test | def visit_JoinedStr(self, node):
"""
Process f-string arguments.
"""
if version_info >= (3, 6):
if self.within_logging_statement():
if any(isinstance(i, FormattedValue) for i in node.values):
if self.within_logging_argument():
... | python | {
"resource": ""
} |
q272323 | LoggingVisitor.visit_keyword | test | def visit_keyword(self, node):
"""
Process keyword arguments.
"""
if self.should_check_whitelist(node):
if node.arg not in self.whitelist and not node.arg.startswith("debug_"):
self.violations.append((self.current_logging_call, WHITELIST_VIOLATION.format(node... | python | {
"resource": ""
} |
q272324 | LoggingVisitor.visit_ExceptHandler | test | def visit_ExceptHandler(self, node):
"""
Process except blocks.
"""
name = self.get_except_handler_name(node)
if not name:
super(LoggingVisitor, self).generic_visit(node)
return
self.current_except_names.append(name)
super(LoggingVisitor,... | python | {
"resource": ""
} |
q272325 | LoggingVisitor.detect_logging_level | test | def detect_logging_level(self, node):
"""
Heuristic to decide whether an AST Call is a logging call.
"""
try:
if self.get_id_attr(node.func.value) == "warnings":
return None
# NB: We could also look at the argument signature or the target attribut... | python | {
"resource": ""
} |
q272326 | LoggingVisitor.get_except_handler_name | test | def get_except_handler_name(self, node):
"""
Helper to get the exception name from an ExceptHandler node in both py2 and py3.
"""
name = node.name
if not name:
return None
if version_info < (3,):
return name.id
return name | python | {
"resource": ""
} |
q272327 | LoggingVisitor.get_id_attr | test | def get_id_attr(self, value):
"""Check if value has id attribute and return it.
:param value: The value to get id from.
:return: The value.id.
"""
if not hasattr(value, "id") and hasattr(value, "value"):
value = value.value
return value.id | python | {
"resource": ""
} |
q272328 | LoggingVisitor.is_bare_exception | test | def is_bare_exception(self, node):
"""
Checks if the node is a bare exception name from an except block.
"""
return isinstance(node, Name) and node.id in self.current_except_names | python | {
"resource": ""
} |
q272329 | LoggingVisitor.check_exc_info | test | def check_exc_info(self, node):
"""
Reports a violation if exc_info keyword is used with logging.error or logging.exception.
"""
if self.current_logging_level not in ('error', 'exception'):
return
for kw in node.keywords:
if kw.arg == 'exc_info':
... | python | {
"resource": ""
} |
q272330 | delete_file_if_needed | test | def delete_file_if_needed(instance, filefield_name):
"""Delete file from database only if needed.
When editing and the filefield is a new file,
deletes the previous file (if any) from the database.
Call this function immediately BEFORE saving the instance.
"""
if instance.pk:
model_clas... | python | {
"resource": ""
} |
q272331 | db_file_widget | test | def db_file_widget(cls):
"""Edit the download-link inner text."""
def get_link_display(url):
unquoted = unquote(url.split('%2F')[-1])
if sys.version_info.major == 2: # python 2
from django.utils.encoding import force_unicode
unquoted = force_unicode(unquoted)
re... | python | {
"resource": ""
} |
q272332 | PDFTemplateResponse.rendered_content | test | def rendered_content(self):
"""Returns the freshly rendered content for the template and context
described by the PDFResponse.
This *does not* set the final content of the response. To set the
response content, you must either call render(), or set the
content explicitly using t... | python | {
"resource": ""
} |
q272333 | PDFTemplateView.render_to_response | test | def render_to_response(self, context, **response_kwargs):
"""
Returns a PDF response with a template rendered with the given context.
"""
filename = response_kwargs.pop('filename', None)
cmd_options = response_kwargs.pop('cmd_options', None)
if issubclass(self.response_c... | python | {
"resource": ""
} |
q272334 | http_quote | test | def http_quote(string):
"""
Given a unicode string, will do its dandiest to give you back a
valid ascii charset string you can use in, say, http headers and the
like.
"""
if isinstance(string, six.text_type):
try:
import unidecode
except ImportError:
pass
... | python | {
"resource": ""
} |
q272335 | configure | test | def configure(module=None, prefix='MONGODB_', **kwargs):
"""Sets defaults for ``class Meta`` declarations.
Arguments can either be extracted from a `module` (in that case
all attributes starting from `prefix` are used):
>>> import foo
>>> configure(foo)
or passed explicictly as keyword argume... | python | {
"resource": ""
} |
q272336 | to_underscore | test | def to_underscore(string):
"""Converts a given string from CamelCase to under_score.
>>> to_underscore('FooBar')
'foo_bar'
"""
new_string = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1_\2', string)
new_string = re.sub(r'([a-z\d])([A-Z])', r'\1_\2', new_string)
return new_string.lower() | python | {
"resource": ""
} |
q272337 | ModelBase.auto_index | test | def auto_index(mcs):
"""Builds all indices, listed in model's Meta class.
>>> class SomeModel(Model)
... class Meta:
... indices = (
... Index('foo'),
... )
.. note:: this will result in calls to
:... | python | {
"resource": ""
} |
q272338 | CsvParser.parse_file | test | def parse_file(self, file_path, currency) -> List[PriceModel]:
""" Load and parse a .csv file """
# load file
# read csv into memory?
contents = self.load_file(file_path)
prices = []
# parse price elements
for line in contents:
price = self.pa... | python | {
"resource": ""
} |
q272339 | CsvParser.load_file | test | def load_file(self, file_path) -> List[str]:
""" Loads the content of the text file """
content = []
content = read_lines_from_file(file_path)
return content | python | {
"resource": ""
} |
q272340 | CsvParser.parse_line | test | def parse_line(self, line: str) -> PriceModel:
""" Parse a CSV line into a price element """
line = line.rstrip()
parts = line.split(',')
result = PriceModel()
# symbol
result.symbol = self.translate_symbol(parts[0])
# value
result.value = Decimal(parts... | python | {
"resource": ""
} |
q272341 | CsvParser.translate_symbol | test | def translate_symbol(self, in_symbol: str) -> str:
""" translate the incoming symbol into locally-used """
# read all mappings from the db
if not self.symbol_maps:
self.__load_symbol_maps()
# translate the incoming symbol
result = self.symbol_maps[in_symbol] if in_sym... | python | {
"resource": ""
} |
q272342 | CsvParser.__load_symbol_maps | test | def __load_symbol_maps(self):
""" Loads all symbol maps from db """
repo = SymbolMapRepository(self.__get_session())
all_maps = repo.get_all()
self.symbol_maps = {}
for item in all_maps:
self.symbol_maps[item.in_symbol] = item.out_symbol | python | {
"resource": ""
} |
q272343 | CsvParser.__get_session | test | def __get_session(self):
""" Reuses the same db session """
if not self.session:
self.session = dal.get_default_session()
return self.session | python | {
"resource": ""
} |
q272344 | add | test | def add(symbol: str, date, value, currency: str):
""" Add individual price """
symbol = symbol.upper()
currency = currency.upper()
app = PriceDbApplication()
price = PriceModel()
# security = SecuritySymbol("", "")
price.symbol.parse(symbol)
# price.symbol.mnemonic = price.symbol.mnemo... | python | {
"resource": ""
} |
q272345 | import_csv | test | def import_csv(filepath: str, currency: str):
""" Import prices from CSV file """
logger.debug(f"currency = {currency}")
# auto-convert to uppercase.
currency = currency.upper()
app = PriceDbApplication()
app.logger = logger
app.import_prices(filepath, currency) | python | {
"resource": ""
} |
q272346 | last | test | def last(symbol: str):
""" displays last price, for symbol if provided """
app = PriceDbApplication()
# convert to uppercase
if symbol:
symbol = symbol.upper()
# extract namespace
sec_symbol = SecuritySymbol("", "")
sec_symbol.parse(symbol)
latest = app.get_late... | python | {
"resource": ""
} |
q272347 | list_prices | test | def list_prices(date, currency, last):
""" Display all prices """
app = PriceDbApplication()
app.logger = logger
if last:
# fetch only the last prices
prices = app.get_latest_prices()
else:
prices = app.get_prices(date, currency)
for price in prices:
print(price)... | python | {
"resource": ""
} |
q272348 | download | test | def download(ctx, help: bool, symbol: str, namespace: str, agent: str, currency: str):
""" Download the latest prices """
if help:
click.echo(ctx.get_help())
ctx.exit()
app = PriceDbApplication()
app.logger = logger
if currency:
currency = currency.strip()
currency ... | python | {
"resource": ""
} |
q272349 | prune | test | def prune(symbol: str, all: str):
""" Delete old prices, leaving just the last. """
app = PriceDbApplication()
app.logger = logger
count = 0
if symbol is not None:
sec_symbol = SecuritySymbol("", "")
sec_symbol.parse(symbol)
deleted = app.prune(sec_symbol)
if delete... | python | {
"resource": ""
} |
q272350 | get_default_session | test | def get_default_session():
""" Return the default session. The path is read from the default config. """
from .config import Config, ConfigKeys
db_path = Config().get(ConfigKeys.price_database)
if not db_path:
raise ValueError("Price database not set in the configuration file!")
return get_... | python | {
"resource": ""
} |
q272351 | add_map | test | def add_map(incoming, outgoing):
""" Creates a symbol mapping """
db_path = Config().get(ConfigKeys.pricedb_path)
session = get_session(db_path)
new_map = SymbolMap()
new_map.in_symbol = incoming
new_map.out_symbol = outgoing
session.add(new_map)
session.commit()
click.echo("Record... | python | {
"resource": ""
} |
q272352 | list_maps | test | def list_maps():
""" Displays all symbol maps """
db_path = Config().get(ConfigKeys.price_database)
session = get_session(db_path)
maps = session.query(SymbolMap).all()
for item in maps:
click.echo(item) | python | {
"resource": ""
} |
q272353 | SymbolMapRepository.get_by_id | test | def get_by_id(self, symbol: str) -> SymbolMap:
""" Finds the map by in-symbol """
return self.query.filter(SymbolMap.in_symbol == symbol).first() | python | {
"resource": ""
} |
q272354 | read_lines_from_file | test | def read_lines_from_file(file_path: str) -> List[str]:
""" Read text lines from a file """
# check if the file exists?
with open(file_path) as csv_file:
content = csv_file.readlines()
return content | python | {
"resource": ""
} |
q272355 | PriceMapper.map_entity | test | def map_entity(self, entity: dal.Price) -> PriceModel:
""" Map the price entity """
if not entity:
return None
result = PriceModel()
result.currency = entity.currency
# date/time
dt_string = entity.date
format_string = "%Y-%m-%d"
if entity.ti... | python | {
"resource": ""
} |
q272356 | PriceMapper.map_model | test | def map_model(self, model: PriceModel) -> Price:
""" Parse into the Price entity, ready for saving """
# assert isinstance(model, PriceModel)
assert isinstance(model.symbol, SecuritySymbol)
assert isinstance(model.datum, Datum)
entity = Price()
# Format date as ISO stri... | python | {
"resource": ""
} |
q272357 | Config.__read_config | test | def __read_config(self, file_path: str):
""" Read the config file """
if not os.path.exists(file_path):
raise FileNotFoundError(f"File path not found: {file_path}")
# check if file exists
if not os.path.isfile(file_path):
self.logger.error(f"file not found: {file_... | python | {
"resource": ""
} |
q272358 | Config.__get_config_template_path | test | def __get_config_template_path(self) -> str:
""" gets the default config path from resources """
filename = resource_filename(
Requirement.parse(package_name),
template_path + config_filename)
return filename | python | {
"resource": ""
} |
q272359 | Config.__create_user_config | test | 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):
message = f"Config template not found {src}"
self.logger.error(message)... | python | {
"resource": ""
} |
q272360 | Config.get_config_path | test | def get_config_path(self) -> str:
"""
Returns the path where the active config file is expected.
This is the user's profile folder.
"""
dst_dir = self.__get_user_path()
dst = dst_dir + "/" + config_filename
return dst | python | {
"resource": ""
} |
q272361 | Config.get_contents | test | def get_contents(self) -> str:
""" Reads the contents of the config file """
content = None
# with open(file_path) as cfg_file:
# contents = cfg_file.read()
# Dump the current contents into an in-memory file.
in_memory = io.StringIO("")
self.config.write(in_m... | python | {
"resource": ""
} |
q272362 | Config.set | test | def set(self, option: ConfigKeys, value):
""" Sets a value in config """
assert isinstance(option, ConfigKeys)
# As currently we only have 1 section.
section = SECTION
self.config.set(section, option.name, value)
self.save() | python | {
"resource": ""
} |
q272363 | Config.get | test | def get(self, option: ConfigKeys):
""" Retrieves a config value """
assert isinstance(option, ConfigKeys)
# Currently only one section is used
section = SECTION
return self.config.get(section, option.name) | python | {
"resource": ""
} |
q272364 | Config.save | test | def save(self):
""" Save the config file """
file_path = self.get_config_path()
contents = self.get_contents()
with open(file_path, mode='w') as cfg_file:
cfg_file.write(contents) | python | {
"resource": ""
} |
q272365 | SecuritySymbol.parse | test | def parse(self, symbol: str) -> (str, str):
""" Splits the symbol into namespace, symbol tuple """
symbol_parts = symbol.split(":")
namespace = None
mnemonic = symbol
if len(symbol_parts) > 1:
namespace = symbol_parts[0]
mnemonic = symbol_parts[1]
... | python | {
"resource": ""
} |
q272366 | PriceDbApplication.add_price | test | def add_price(self, price: PriceModel):
""" Creates a new price record """
# assert isinstance(price, PriceModel)
if not price:
raise ValueError("Cannot add price. The received model is null!")
mapper = mappers.PriceMapper()
entity = mapper.map_model(price)
... | python | {
"resource": ""
} |
q272367 | PriceDbApplication.add_price_entity | test | def add_price_entity(self, price: dal.Price):
""" Adds the price """
from decimal import Decimal
# check if the price already exists in db.
repo = self.get_price_repository()
existing = (
repo.query
.filter(dal.Price.namespace == price.namespace)
... | python | {
"resource": ""
} |
q272368 | PriceDbApplication.download_price | test | def download_price(self, symbol: str, currency: str, agent: str) -> PriceModel:
""" Download and save price online """
price = self.__download_price(symbol, currency, agent)
self.save()
return price | python | {
"resource": ""
} |
q272369 | PriceDbApplication.session | test | def session(self):
""" Returns the current db session """
if not self.__session:
self.__session = dal.get_default_session()
return self.__session | python | {
"resource": ""
} |
q272370 | PriceDbApplication.get_prices | test | def get_prices(self, date: str, currency: str) -> List[PriceModel]:
""" Fetches all the prices for the given arguments """
from .repositories import PriceRepository
session = self.session
repo = PriceRepository(session)
query = repo.query
if date:
query = que... | python | {
"resource": ""
} |
q272371 | PriceDbApplication.get_prices_on | test | def get_prices_on(self, on_date: str, namespace: str, symbol: str):
""" Returns the latest price on the date """
repo = self.get_price_repository()
query = (
repo.query.filter(dal.Price.namespace == namespace)
.filter(dal.Price.symbol == symbol)
.filter(dal.Pr... | python | {
"resource": ""
} |
q272372 | PriceDbApplication.prune_all | test | def prune_all(self) -> int:
"""
Prune historical prices for all symbols, leaving only the latest.
Returns the number of items removed.
"""
from .repositories import PriceRepository
# get all symbols that have prices
repo = PriceRepository()
items = repo.q... | python | {
"resource": ""
} |
q272373 | PriceDbApplication.prune | test | def prune(self, symbol: SecuritySymbol):
"""
Delete all but the latest available price for the given symbol.
Returns the number of items removed.
"""
from .repositories import PriceRepository
assert isinstance(symbol, SecuritySymbol)
self.logger.debug(f"pruning ... | python | {
"resource": ""
} |
q272374 | PriceDbApplication.__download_price | test | def __download_price(self, symbol: str, currency: str, agent: str):
""" Downloads and parses the price """
from finance_quote_python import Quote
assert isinstance(symbol, str)
assert isinstance(currency, str)
assert isinstance(agent, str)
if not symbol:
ret... | python | {
"resource": ""
} |
q272375 | PriceDbApplication.__get_securities | test | def __get_securities(self, currency: str, agent: str, symbol: str,
namespace: str) -> List[dal.Security]:
""" Fetches the securities that match the given filters """
repo = self.get_security_repository()
query = repo.query
if currency is not None:
qu... | python | {
"resource": ""
} |
q272376 | Node.partial | test | def partial(self):
"""Return partial of original function call"""
ba = self.data["bound_args"]
return state_partial(self.data["func"], *ba.args[1:], **ba.kwargs) | python | {
"resource": ""
} |
q272377 | Node.update_child_calls | test | def update_child_calls(self):
"""Replace child nodes on original function call with their partials"""
for node in filter(lambda n: len(n.arg_name), self.child_list):
self.data["bound_args"].arguments[node.arg_name] = node.partial()
self.updated = True | python | {
"resource": ""
} |
q272378 | Node.descend | test | def descend(self, include_me=True):
"""Descend depth first into all child nodes"""
if include_me:
yield self
for child in self.child_list:
yield child
yield from child.descend() | python | {
"resource": ""
} |
q272379 | multi_dec | test | def multi_dec(f):
"""Decorator for multi to remove nodes for original test functions from root node"""
@wraps(f)
def wrapper(*args, **kwargs):
args = (
args[0] if len(args) == 1 and isinstance(args[0], (list, tuple)) else args
)
for arg in args:
if isinstance... | python | {
"resource": ""
} |
q272380 | has_equal_part_len | test | def has_equal_part_len(state, name, unequal_msg):
"""Verify that a part that is zoomed in on has equal length.
Typically used in the context of ``check_function_def()``
Arguments:
name (str): name of the part for which to check the length to the corresponding part in the solution.
unequal_... | python | {
"resource": ""
} |
q272381 | has_equal_ast | test | def has_equal_ast(state, incorrect_msg=None, code=None, exact=True, append=None):
"""Test whether abstract syntax trees match between the student and solution code.
``has_equal_ast()`` can be used in two ways:
* As a robust version of ``has_code()``. By setting ``code``, you can look for the AST represent... | python | {
"resource": ""
} |
q272382 | has_code | test | def has_code(state, text, pattern=True, not_typed_msg=None):
"""Test the student code.
Tests if the student typed a (pattern of) text. It is advised to use ``has_equal_ast()`` instead of ``has_code()``,
as it is more robust to small syntactical differences that don't change the code's behavior.
Args:
... | python | {
"resource": ""
} |
q272383 | has_import | test | def has_import(
state,
name,
same_as=False,
not_imported_msg="Did you import `{{pkg}}`?",
incorrect_as_msg="Did you import `{{pkg}}` as `{{alias}}`?",
):
"""Checks whether student imported a package or function correctly.
Python features many ways to import packages.
All of these differ... | python | {
"resource": ""
} |
q272384 | has_output | test | def has_output(state, text, pattern=True, no_output_msg=None):
"""Search student output for a pattern.
Among the student and solution process, the student submission and solution code as a string,
the ``Ex()`` state also contains the output that a student generated with his or her submission.
With ``h... | python | {
"resource": ""
} |
q272385 | has_printout | test | def has_printout(
state, index, not_printed_msg=None, pre_code=None, name=None, copy=False
):
"""Check if the right printouts happened.
``has_printout()`` will look for the printout in the solution code that you specified with ``index`` (0 in this case), rerun the ``print()`` call in
the solution proce... | python | {
"resource": ""
} |
q272386 | has_no_error | test | def has_no_error(
state,
incorrect_msg="Have a look at the console: your code contains an error. Fix it and try again!",
):
"""Check whether the submission did not generate a runtime error.
If all SCTs for an exercise pass, before marking the submission as correct pythonwhat will automatically check wh... | python | {
"resource": ""
} |
q272387 | has_chosen | test | def has_chosen(state, correct, msgs):
"""Test multiple choice exercise.
Test for a MultipleChoiceExercise. The correct answer (as an integer) and feedback messages
are passed to this function.
Args:
correct (int): the index of the correct answer (should be an instruction). Starts at 1.
... | python | {
"resource": ""
} |
q272388 | check_function | test | def check_function(
state,
name,
index=0,
missing_msg=None,
params_not_matched_msg=None,
expand_msg=None,
signature=True,
):
"""Check whether a particular function is called.
``check_function()`` is typically followed by:
- ``check_args()`` to check whether the arguments we... | python | {
"resource": ""
} |
q272389 | getResultFromProcess | test | def getResultFromProcess(res, tempname, process):
"""Get a value from process, return tuple of value, res if succesful"""
if not isinstance(res, (UndefinedValue, Exception)):
value = getRepresentation(tempname, process)
return value, res
else:
return res, str(res) | python | {
"resource": ""
} |
q272390 | override | test | def override(state, solution):
"""Override the solution code with something arbitrary.
There might be cases in which you want to temporarily override the solution code
so you can allow for alternative ways of solving an exercise.
When you use ``override()`` in an SCT chain, the remainder of that SCT ch... | python | {
"resource": ""
} |
q272391 | is_instance | test | def is_instance(state, inst, not_instance_msg=None):
"""Check whether an object is an instance of a certain class.
``is_instance()`` can currently only be used when chained from ``check_object()``, the function that is
used to 'zoom in' on the object of interest.
Args:
inst (class): The class ... | python | {
"resource": ""
} |
q272392 | TargetVars.defined_items | test | def defined_items(self):
"""Return copy of instance, omitting entries that are EMPTY"""
return self.__class__(
[(k, v) for k, v in self.items() if v is not self.EMPTY], is_empty=False
) | python | {
"resource": ""
} |
q272393 | State.to_child | test | def to_child(self, append_message="", node_name="", **kwargs):
"""Dive into nested tree.
Set the current state as a state with a subtree of this syntax tree as
student tree and solution tree. This is necessary when testing if statements or
for loops for example.
"""
base... | python | {
"resource": ""
} |
q272394 | Dispatcher._getx | test | def _getx(self, Parser, ext_attr, tree):
"""getter for Parser outputs"""
# return cached output if possible
cache_key = Parser.__name__ + str(hash(tree))
if self._parser_cache.get(cache_key):
p = self._parser_cache[cache_key]
else:
# otherwise, run parser ... | python | {
"resource": ""
} |
q272395 | has_context_loop | test | def has_context_loop(state, incorrect_msg, exact_names):
"""When dispatched on loops, has_context the target vars are the attribute _target_vars.
Note: This is to allow people to call has_context on a node (e.g. for_loop) rather than
one of its attributes (e.g. body). Purely for convenience.
"""
... | python | {
"resource": ""
} |
q272396 | has_context_with | test | def has_context_with(state, incorrect_msg, exact_names):
"""When dispatched on with statements, has_context loops over each context manager.
Note: This is to allow people to call has_context on the with statement, rather than
having to manually loop over each context manager.
e.g. Ex().che... | python | {
"resource": ""
} |
q272397 | check_part | test | def check_part(state, name, part_msg, missing_msg=None, expand_msg=None):
"""Return child state with name part as its ast tree"""
if missing_msg is None:
missing_msg = "Are you sure you defined the {{part}}? "
if expand_msg is None:
expand_msg = "Did you correctly specify the {{part}}? "
... | python | {
"resource": ""
} |
q272398 | check_part_index | test | def check_part_index(state, name, index, part_msg, missing_msg=None, expand_msg=None):
"""Return child state with indexed name part as its ast tree.
``index`` can be:
- an integer, in which case the student/solution_parts are indexed by position.
- a string, in which case the student/solution_parts ar... | python | {
"resource": ""
} |
q272399 | check_args | test | def check_args(state, name, missing_msg=None):
"""Check whether a function argument is specified.
This function can follow ``check_function()`` in an SCT chain and verifies whether an argument is specified.
If you want to go on and check whether the argument was correctly specified, you can can continue ch... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.