_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
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 +
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: #
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:
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: rates[date] = None if self.verbose: missing = len([r for r in itervalues(rates) if r is None])
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 closest rates forward and backward tmp = defaultdict(lambda: [None, None]) for date in sorted(rates): rate = rates[date] if rate is not None: closest_rate = rate dist = 0 else: dist += 1 tmp[date][0] = closest_rate, dist for date in sorted(rates, reverse=True): rate = rates[date] if rate is not None:
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, 11, 21)) Traceback (most recent call last): RateNotFoundError: BGN has no rate for 2010-11-21 """ if currency == self.ref_currency: return 1.0 if date not in self._rates[currency]: first_date, last_date = self.bounds[currency] if not self.fallback_on_wrong_date: raise RateNotFoundError('{0} not in {1} bounds {2}/{3}'.format( date, currency, first_date, last_date)) if date < first_date: fallback_date = first_date elif date > last_date: fallback_date = last_date
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. :param datetime.date date: Use the conversion rate of this date. If this is not given, the most recent rate is used. :return: The value of `amount` in `new_currency`. :rtype: float >>> from datetime import date >>> c = CurrencyConverter()
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
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
python
{ "resource": "" }
q272309
DAF.read_record
test
def read_record(self, n): """Return record `n` as 1,024 bytes; records are indexed from 1."""
python
{ "resource": "" }
q272310
DAF.write_record
test
def write_record(self, n, data): """Write `data` to file record `n`; records are indexed from 1."""
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. Memory maps must begin on a page boundary, so `skip` returns the number of extra bytes at the beginning of the return value.
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')].decode('ascii').replace('\0', '\n')
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 = self.file scs = self.summary_control_struct record_number = self.bward data = bytearray(self.read_record(record_number)) next_record, previous_record, n_summaries = scs.unpack(data[:24]) if n_summaries < self.summaries_per_record: summary_record = record_number name_record = summary_record + 1 data[:24] = scs.pack(next_record, previous_record, n_summaries + 1) self.write_record(summary_record, data) else: summary_record = ((self.free - 1) * 8 + 1023) // 1024 + 1 name_record = summary_record + 1 free_record = summary_record + 2 n_summaries = 0 data[:24] = scs.pack(summary_record, previous_record, n_summaries) self.write_record(record_number, data) summaries = scs.pack(0, record_number, 1).ljust(1024, b'\0') names = b'\0' * 1024 self.write_record(summary_record, summaries)
python
{ "resource": "" }
q272314
SPK.close
test
def close(self): """Close this SPK file.""" self.daf.file.close() for segment in self.segments:
python
{ "resource": "" }
q272315
Segment.compute
test
def compute(self, tdb, tdb2=0.0): """Compute the component values for the
python
{ "resource": "" }
q272316
BinaryPCK.close
test
def close(self): """Close this file.""" self.daf.file.close() for segment in self.segments:
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.end_i) initial_epoch = jd(init) interval_length = intlen / S_PER_DAY coefficient_count = int(rsize - 2) // component_count
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) and not getattr(tdb2, 'shape', 0) if scalar: tdb = array((tdb,)) data = self._data if data is None: self._data = data = self._load() initial_epoch, interval_length, coefficients = data component_count, n, coefficient_count = coefficients.shape # Subtracting tdb before adding tdb2 affords greater precision. index, offset = divmod((tdb - initial_epoch) + tdb2, interval_length) index = index.astype(int) if (index < 0).any() or (index > n).any(): final_epoch = initial_epoch + interval_length * n raise ValueError('segment only covers dates %.1f through %.1f' % (initial_epoch, final_epoch)) omegas = (index == n) index[omegas] -= 1 offset[omegas] += interval_length coefficients = coefficients[:,index] # Chebyshev polynomial. T = empty((coefficient_count, len(index)))
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_format_call(node): self.violations.append((node, STRING_FORMAT_VIOLATION)) super(LoggingVisitor, self).generic_visit(node) return logging_level = self.detect_logging_level(node) if logging_level and self.current_logging_level is None: self.current_logging_level = logging_level # CASE 2: We're in some other statement if logging_level is None: super(LoggingVisitor, self).generic_visit(node) return # CASE 3: We're entering a new logging statement self.current_logging_call = node if logging_level == "warn": self.violations.append((node, WARN_VIOLATION)) self.check_exc_info(node) for index, child in enumerate(iter_child_nodes(node)):
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.append((node, PERCENT_FORMAT_VIOLATION))
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
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):
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.arg)))
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
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
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:
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
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. """
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': if self.current_logging_level == 'error':
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_class = type(instance) # Check if there is a file for the instance in the database if model_class.objects.filter(pk=instance.pk).exclude( **{'%s__isnull' % filefield_name: True} ).exclude( **{'%s__exact' % filefield_name: ''} ).exists(): old_file = getattr( model_class.objects.only(filefield_name).get(pk=instance.pk), filefield_name ) else: old_file = None # If there is a file, delete it if needed if old_file:
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) return escape(unquoted) def get_template_substitution_values(self, value): # Used by Django < 1.11 subst = super(cls, self).get_template_substitution_values(value) subst['initial'] = get_link_display(value.url) return subst setattr(cls, 'get_template_substitution_values',
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 the value of this property.
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_class, PDFTemplateResponse): if filename is None: filename = self.get_filename() if cmd_options is None: cmd_options = self.get_cmd_options() return super(PDFTemplateView, self).render_to_response( context=context, filename=filename, show_content_in_browser=self.show_content_in_browser,
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 else: string = unidecode.unidecode(string)
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 arguments: >>> configure(database='foo') .. warning:: Current implementation is by no means thread-safe -- use it wisely. """ if module is not None and isinstance(module, types.ModuleType): # Search module for MONGODB_* attributes and converting them # to _Options'
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)
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 :meth:`pymongo.collection.Collection.ensure_index`
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:
python
{ "resource": "" }
q272339
CsvParser.load_file
test
def load_file(self, file_path) -> List[str]: """ Loads the content of the text file """ 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[1]) # date date_str = parts[2] date_str = date_str.replace('"', '') date_parts = date_str.split('/') year_str = date_parts[2]
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
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()
python
{ "resource": "" }
q272343
CsvParser.__get_session
test
def __get_session(self): """ Reuses the same db session """ if not 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.mnemonic.upper() # date_str = f"{date}" # date_format = "%Y-%m-%d" # if time: # date_str = f"{date_str}T{time}"
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()
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_latest_price(sec_symbol) assert isinstance(latest, PriceModel)
python
{ "resource": "" }
q272347
list_prices
test
def list_prices(date, currency, last): """ Display all prices """ app = PriceDbApplication() app.logger = logger if last: #
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)
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:
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
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)
python
{ "resource": "" }
q272353
SymbolMapRepository.get_by_id
test
def get_by_id(self, symbol: str) -> SymbolMap: """ Finds the map by in-symbol """
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
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.time: dt_string += f"T{entity.time}"
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 string date_iso = f"{model.datum.value.year}-{model.datum.value.month:02d}-{model.datum.value.day:02d}" entity.date = date_iso entity.time = f"{model.datum.value.hour:02d}:{model.datum.value.minute:02d}:{model.datum.value.second:02d}" # Symbol # properly mapped symbols have a namespace, except for the US markets # TODO check this with .csv import if model.symbol.namespace: entity.namespace = model.symbol.namespace.upper()
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):
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(
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.
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_memory)
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.
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
python
{ "resource": "" }
q272364
Config.save
test
def save(self): """ Save the config file """ file_path = self.get_config_path() contents = self.get_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:
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:
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) .filter(dal.Price.symbol == price.symbol) .filter(dal.Price.date == price.date) .filter(dal.Price.time == price.time) .first()
python
{ "resource": "" }
q272368
PriceDbApplication.download_price
test
def download_price(self, symbol: str, currency: str, agent: str) -> PriceModel: """ Download and
python
{ "resource": "" }
q272369
PriceDbApplication.session
test
def session(self): """ Returns the current db session """ if not self.__session: 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 = query.filter(dal.Price.date == date) if currency: query = query.filter(dal.Price.currency == currency)
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
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.query.distinct(dal.Price.namespace, dal.Price.symbol).all() # self.logger.debug(items)
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 prices for {symbol}") repo = PriceRepository() query = ( repo.query.filter(dal.Price.namespace == symbol.namespace) .filter(dal.Price.symbol == symbol.mnemonic) .order_by(dal.Price.date.desc()) .order_by(dal.Price.time.desc()) ) all_prices = query.all() # self.logger.debug(f"fetched
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: return None #self.logger.info(f"Downloading {symbol}... ") dl = Quote() dl.logger = self.logger dl.set_source(agent) dl.set_currency(currency) result = dl.fetch(agent, [symbol]) if not result:
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: query = query.filter(dal.Security.currency == currency) if agent is not None: query = query.filter(dal.Security.updater == agent) if symbol is not None: query = query.filter(dal.Security.symbol == symbol)
python
{ "resource": "" }
q272376
Node.partial
test
def partial(self): """Return partial of original function call""" ba = self.data["bound_args"]
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):
python
{ "resource": "" }
q272378
Node.descend
test
def descend(self, include_me=True): """Descend depth first into all child nodes"""
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:
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_msg (str): Message in case the lengths do not match. state (State): state as passed by the SCT chain. Don't specify this explicitly. :Examples: Student and solution code:: def shout(word): return word + '!!!'
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 representation of ``code`` in the student's submission. But be aware that ``a`` and ``a = 1`` won't match, as reading and assigning are not the same in an AST. Use ``ast.dump(ast.parse(code))`` to see an AST representation of ``code``. * As an expression-based check when using more advanced SCT chain, e.g. to compare the equality of expressions to set function arguments. Args: incorrect_msg: message displayed when ASTs mismatch. When you specify ``code`` yourself, you have to specify this. code: optional code to use instead of the solution AST. exact: whether the representations must match exactly. If false, the solution AST only needs to be contained within the student AST (similar to using test student typed). Defaults to ``True``, unless the ``code`` argument has been specified. :Example: Student and Solution Code:: dict(a = 'value').keys() SCT:: # all pass Ex().has_equal_ast() Ex().has_equal_ast(code = "dict(a = 'value').keys()") Ex().has_equal_ast(code = "dict(a = 'value')", exact = False) Student and Solution Code:: import numpy as np arr = np.array([1, 2, 3, 4, 5]) np.mean(arr) SCT:: # Check underlying value of arugment a of np.mean: Ex().check_function('numpy.mean').check_args('a').has_equal_ast() # Only check AST equality of expression used to specify argument a: Ex().check_function('numpy.mean').check_args('a').has_equal_ast() """ if utils.v2_only(): state.assert_is_not(["object_assignments"], "has_equal_ast", ["check_object"]) state.assert_is_not(["function_calls"], "has_equal_ast", ["check_function"]) if code and incorrect_msg is None: raise InstructorError( "If you manually specify the code to match inside has_equal_ast(), " "you have to explicitly set the `incorrect_msg` argument." ) if ( append is None
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: text (str): the text that is searched for pattern (bool): if True (the default), the text is treated as a pattern. If False, it is treated as plain text. not_typed_msg (str): feedback message to be displayed if the
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 different methods revolve around the ``import``, ``from`` and ``as`` keywords. ``has_import()`` provides a robust way to check whether a student correctly imported a certain package. By default, ``has_import()`` allows for different ways of aliasing the imported package or function. If you want to make sure the correct alias was used to refer to the package or function that was imported, set ``same_as=True``. Args: name (str): the name of the package that has to be checked. same_as (bool): if True, the alias of the package or function has to be the same. Defaults to False. not_imported_msg (str): feedback message when the package is not imported. incorrect_as_msg (str): feedback message if the alias is wrong. :Example: Example 1, where aliases don't matter (defaut): :: # solution import matplotlib.pyplot as plt # sct Ex().has_import("matplotlib.pyplot") # passing submissions import matplotlib.pyplot as plt from matplotlib import pyplot as plt import matplotlib.pyplot as pltttt # failing submissions import matplotlib as mpl Example 2, where the SCT is coded so aliases do matter: :: # solution import matplotlib.pyplot as plt # sct Ex().has_import("matplotlib.pyplot", same_as=True) # passing submissions import matplotlib.pyplot
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 ``has_output()``, you can access this output and match it against a regular or fixed expression. Args: text (str): the text that is searched for pattern (bool): if True (default), the text is treated as a pattern. If False, it is treated as plain text. no_output_msg (str): feedback message to be displayed if the output is not found. :Example: As an example, suppose we want a student to print out a sentence: :: # Print the "This is some ... stuff" print("This is some weird stuff") The following SCT tests whether the student prints out ``This is some weird stuff``: :: # Using exact string matching Ex().has_output("This is some weird stuff", pattern = False)
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 process, capture its output, and verify whether the output is present in the output of the student. This is more robust as ``Ex().check_function('print')`` initiated chains as students can use as many printouts as they want, as long as they do the correct one somewhere. Args: index (int): index of the ``print()`` call in the solution whose output you want to search for in the student output. not_printed_msg (str): if specified, this overrides the default message that is generated when the output is not found in the student output. pre_code (str): Python code as a string that is executed before running the targeted student call. This is the ideal place to set a random seed, for example. copy (bool): whether to try to deep copy objects in the environment, such as lists, that could accidentally be mutated. Disabled by default, which speeds up SCTs. state (State): state as passed by the SCT chain. Don't specify this explicitly. :Example: Suppose you want somebody to print out 4: :: print(1, 2, 3, 4) The following SCT would check that: :: Ex().has_printout(0) All of the following SCTs would pass: :: print(1, 2, 3, 4) print('1 2 3 4') print(1, 2, '3 4') print("random"); print(1, 2, 3, 4) :Example: Watch out: ``has_printout()`` will effectively **rerun** the ``print()`` call in the solution process after the entire solution script was executed. If your solution script updates the value of `x` after executing it, ``has_printout()`` will not work. Suppose you have the following solution: :: x = 4 print(x) x = 6 The following SCT will not work: :: Ex().has_printout(0) Why? When the ``print(x)`` call is executed, the value of ``x`` will be 6, and pythonwhat will look for the output `'6`' in the output the student generated. In cases like these, ``has_printout()`` cannot be used. :Example: Inside a for loop ``has_printout()`` Suppose you have the following solution: :: for i in range(5): print(i) The following SCT will not work: :: Ex().check_for_loop().check_body().has_printout(0) The reason is that
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 whether the student submission generated an error. This means it is not needed to use ``has_no_error()`` explicitly. However, in some cases, using ``has_no_error()`` explicitly somewhere throughout your SCT execution can be helpful: - If you want to make sure people didn't write typos when writing a long function name. - If you want to first verify whether a function actually runs, before checking whether the arguments were specified correctly. - More generally, if, because of the content, it's instrumental that the script runs without errors before doing any other verifications. Args: incorrect_msg: if specified, this overrides the default message if the student code generated an error. :Example: Suppose you're verifying an exercise about model training and validation: ::
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. msgs (list(str)): a list containing all feedback messages belonging to each choice of the student. The list should have the same length as the number of options. """ if not issubclass(type(correct), int): raise InstructorError( "Inside `has_chosen()`, the argument `correct` should be an integer." ) student_process = state.student_process if not isDefinedInProcess(MC_VAR_NAME, student_process): raise InstructorError("Option not available in the student process") else: selected_option = getOptionFromProcess(student_process, MC_VAR_NAME) if not
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 were specified. In turn, ``check_args()`` can be followed by ``has_equal_value()`` or ``has_equal_ast()`` to assert that the arguments were correctly specified. - ``has_equal_value()`` to check whether rerunning the function call coded by the student gives the same result as calling the function call as in the solution. Checking function calls is a tricky topic. Please visit the `dedicated article <articles/checking_function_calls.html>`_ for more explanation, edge cases and best practices. Args: name (str): the name of the function to be tested. When checking functions in packages, always use the 'full path' of the function. index (int): index of the function call to be checked. Defaults to 0. missing_msg (str): If specified, this overrides an automatically generated feedback message in case the student did not call the function correctly. params_not_matched_msg (str): If specified, this overrides an automatically generated feedback message in case the function parameters were not successfully matched. expand_msg (str): If specified, this overrides any messages that are prepended by previous SCT chains. signature (Signature): Normally, check_function() can figure out what the function signature is, but it might be necessary to use ``sig_from_params()`` to manually build a signature and pass this along. state (State): State object that is passed from the SCT Chain (don't specify this). :Examples: Student code and solution code:: import numpy as np arr = np.array([1, 2, 3, 4, 5]) np.mean(arr) SCT:: # Verify whether arr was correctly set in np.mean Ex().check_function('numpy.mean').check_args('a').has_equal_value() # Verify whether np.mean(arr) produced the same result Ex().check_function('numpy.mean').has_equal_value() """ append_missing = missing_msg is None append_params_not_matched = params_not_matched_msg is None if missing_msg is None: missing_msg = MISSING_MSG if expand_msg is None: expand_msg = PREPEND_MSG if params_not_matched_msg is None: params_not_matched_msg = SIG_ISSUE_MSG stu_out = state.ast_dispatcher("function_calls", state.student_ast) sol_out = state.ast_dispatcher("function_calls", state.solution_ast) student_mappings = state.ast_dispatcher("mappings", state.student_ast) fmt_kwargs = { "times": get_times(index + 1), "ord": get_ord(index + 1), "index": index, "mapped_name": get_mapped_name(name, student_mappings), } # Get Parts ---- # Copy, otherwise signature binding overwrites sol_out[name][index]['args'] try: sol_parts = {**sol_out[name][index]} except KeyError: raise InstructorError( "`check_function()` couldn't find a call of `%s()` in the solution code. Make sure you get the mapping right!"
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
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 chain will run as if the solution code you specified is the only code that was in the solution. Check the glossary for an example (pandas plotting) Args: solution: solution code as a string that overrides the original solution code. state: State instance describing student and solution code. Can be omitted if used with Ex(). """ # the old ast may be a number of node types, but generally either a # (1) ast.Module, or for single expressions... # (2) whatever was grabbed using module.body[0] # (3) module.body[0].value, when module.body[0] is an Expr node old_ast
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 that the object should have. not_instance_msg (str): When specified, this overrides the automatically generated message in case the object does not have the expected class. state (State): The state that is passed in through the SCT chain (don't specify this). :Example: Student code and solution code::
python
{ "resource": "" }
q272392
TargetVars.defined_items
test
def defined_items(self): """Return copy of instance, omitting entries that are EMPTY""" return self.__class__(
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_kwargs = { attr: getattr(self, attr) for attr in self.params if attr not in ["highlight"] } if not isinstance(append_message, dict): append_message = {"msg": append_message, "kwargs": {}} kwargs["messages"] = [*self.messages, append_message] kwargs["parent_state"] = self for kwarg in ["solution_context", "student_context"]: if kwarg in kwargs and not kwargs[kwarg]: kwargs.pop(kwarg, None) def update_kwarg(name, func): kwargs[name] = func(kwargs[name]) def update_context(name): update_kwarg(name, getattr(self, name).update_ctx) if isinstance(kwargs.get("student_ast", None), list): update_kwarg("student_ast", wrap_in_module) if isinstance(kwargs.get("solution_ast", None), list): update_kwarg("solution_ast", wrap_in_module) if "student_ast" in kwargs: kwargs["student_code"] = self.student_ast_tokens.get_text( kwargs["student_ast"]
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 over tree p = Parser() # set mappings for parsers that inspect attribute access if ext_attr != "mappings" and Parser in [
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. """ return
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
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}}? " if not part_msg: part_msg = name append_message = {"msg": expand_msg, "kwargs": {"part": part_msg}}
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 are expected to be a dictionary. - a list of indices (which can be integer or string), in which case the student parts are indexed step by step. """ 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}}? " # create message ordinal = get_ord(index + 1) if isinstance(index, int) else "" fmt_kwargs = {"index": index, "ordinal": ordinal} fmt_kwargs.update(part=render(part_msg, fmt_kwargs)) append_message = {"msg": expand_msg, "kwargs": fmt_kwargs} # check there are enough parts
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 chaining with ``has_equal_value()`` (value-based check) or ``has_equal_ast()`` (AST-based check) This function can also follow ``check_function_def()`` or ``check_lambda_function()`` to see if arguments have been specified. Args: name (str): the name of the argument for which you want to check it is specified. This can also be a number, in which case it refers to the positional arguments. Named argumetns take precedence. missing_msg (str): If specified, this overrides an automatically generated feedback message in case the student did specify the argument. state (State): State object that is passed from the SCT Chain (don't specify this). :Examples: Student and solution code:: import numpy as np arr = np.array([1, 2, 3, 4, 5])
python
{ "resource": "" }