_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q275800 | Gateway.receiver_blueprints | test | def receiver_blueprints(self):
""" Get Flask blueprints for every provider that supports it
Note: this requires Flask microframework.
:rtype: dict
:returns: A dict { provider-name: Blueprint }
"""
blueprints = {}
for name in self._providers:
... | python | {
"resource": ""
} |
q275801 | IProvider._receive_message | test | def _receive_message(self, message):
""" Incoming message callback
Calls Gateway.onReceive event hook
Providers are required to:
* Cast phone numbers to digits-only
* Support both ASCII and Unicode messages
* Populate `message.msgid` and `message.met... | python | {
"resource": ""
} |
q275802 | IProvider._receive_status | test | def _receive_status(self, status):
""" Incoming status callback
Calls Gateway.onStatus event hook
Providers are required to:
* Cast phone numbers to digits-only
* Use proper MessageStatus subclasses
* Populate `status.msgid` and `status.meta` fields
... | python | {
"resource": ""
} |
q275803 | jsonex_api | test | def jsonex_api(f):
""" View wrapper for JsonEx responses. Catches exceptions as well """
@wraps(f)
def wrapper(*args, **kwargs):
# Call, catch exceptions
try:
code, res = 200, f(*args, **kwargs)
except HTTPException as e:
code, res = e.code, {'error': e}
... | python | {
"resource": ""
} |
q275804 | ForwardServerProvider.forward | test | def forward(self, obj):
""" Forward an object to clients.
:param obj: The object to be forwarded
:type obj: smsframework.data.IncomingMessage|smsframework.data.MessageStatus
:raises Exception: if any of the clients failed
"""
assert isinstance(obj, (IncomingMessage, Mess... | python | {
"resource": ""
} |
q275805 | SafeCreationTx._sign_web3_transaction | test | def _sign_web3_transaction(tx: Dict[str, any], v: int, r: int, s: int) -> (bytes, HexBytes):
"""
Signed transaction that compatible with `w3.eth.sendRawTransaction`
Is not used because `pyEthereum` implementation of Transaction was found to be more
robust regarding invalid signatures
... | python | {
"resource": ""
} |
q275806 | SafeService.estimate_tx_gas_with_web3 | test | def estimate_tx_gas_with_web3(self, safe_address: str, to: str, value: int, data: bytes) -> int:
"""
Estimate tx gas using web3
"""
return self.ethereum_client.estimate_gas(safe_address, to, value, data, block_identifier='pending') | python | {
"resource": ""
} |
q275807 | SafeService.estimate_tx_gas | test | def estimate_tx_gas(self, safe_address: str, to: str, value: int, data: bytes, operation: int) -> int:
"""
Estimate tx gas. Use the max of calculation using safe method and web3 if operation == CALL or
use just the safe calculation otherwise
"""
# Costs to route through the proxy... | python | {
"resource": ""
} |
q275808 | AbstractAsyncWrapper.write | test | async def write(self, towrite: bytes, await_blocking=False):
"""
Appends towrite to the write queue
>>> await test.write(b"HELLO")
# Returns without wait time
>>> await test.write(b"HELLO", await_blocking = True)
# Returns when the bufer is flushed
:param towrit... | python | {
"resource": ""
} |
q275809 | Serial.readline | test | async def readline(self) -> bytes:
"""
Reads one line
>>> # Keeps waiting for a linefeed incase there is none in the buffer
>>> await test.readline()
:returns: bytes forming a line
"""
while True:
line = self._serial_instance.readline()
i... | python | {
"resource": ""
} |
q275810 | Connection.send | test | def send(self, message):
"""Verifies and sends message.
:param message: Message instance.
:param envelope_from: Email address to be used in MAIL FROM command.
"""
assert message.send_to, "No recipients have been added"
if message.has_bad_headers(self.mail.default_sender... | python | {
"resource": ""
} |
q275811 | Message.as_string | test | def as_string(self, default_from=None):
"""Creates the email"""
encoding = self.charset or 'utf-8'
attachments = self.attachments or []
if len(attachments) == 0 and not self.html:
# No html content and zero attachments means plain text
msg = self._mimetext(self... | python | {
"resource": ""
} |
q275812 | Message.has_bad_headers | test | def has_bad_headers(self, default_from=None):
"""Checks for bad headers i.e. newlines in subject, sender or recipients.
"""
sender = self.sender or default_from
reply_to = self.reply_to or ''
for val in [self.subject, sender, reply_to] + self.recipients:
for c in '\r... | python | {
"resource": ""
} |
q275813 | Message.attach | test | def attach(self,
filename=None,
content_type=None,
data=None,
disposition=None,
headers=None):
"""Adds an attachment to the message.
:param filename: filename of attachment
:param content_type: file mimetype
:par... | python | {
"resource": ""
} |
q275814 | DataAccessLayer.register_services | test | def register_services(self, **services):
"""
Register Services that can be accessed by this DAL. Upon
registration, the service is set up.
:param **services: Keyword arguments where the key is the name
to register the Service as and the value is the Service.
"""
... | python | {
"resource": ""
} |
q275815 | from_module | test | def from_module(module_name):
"""
Load a configuration module and return a Config
"""
d = importlib.import_module(module_name)
config = {}
for key in dir(d):
if key.isupper():
config[key] = getattr(d, key)
return Config(config) | python | {
"resource": ""
} |
q275816 | ResourceManager.register_resources | test | def register_resources(self, **resources):
"""
Register resources with the ResourceManager.
"""
for key, resource in resources.items():
if key in self._resources:
raise AlreadyExistsException('A Service for {} is already registered.'.format(key))
... | python | {
"resource": ""
} |
q275817 | Meta.require | test | def require(self, key):
"""
Raises an exception if value for ``key`` is empty.
"""
value = self.get(key)
if not value:
raise ValueError('"{}" is empty.'.format(key))
return value | python | {
"resource": ""
} |
q275818 | DataAccessContext._exit | test | def _exit(self, obj, type, value, traceback):
"""
Teardown a Resource or Middleware.
"""
if type is None:
# No in-context exception occurred
try:
obj.next()
except StopIteration:
# Resource closed as expected
... | python | {
"resource": ""
} |
q275819 | Service.setup | test | def setup(self, data_manager):
"""
Hook to setup this service with a specific DataManager.
Will recursively setup sub-services.
"""
self._data_manager = data_manager
if self._data_manager:
self._dal = self._data_manager.get_dal()
else:
sel... | python | {
"resource": ""
} |
q275820 | _Material.ng | test | def ng(self, wavelength):
'''
The group index with respect to wavelength.
Args:
wavelength (float, list, None): The wavelength(s) the group
index will be evaluated at.
Returns:
float, list: The group index at the target wavelength(s).
'''... | python | {
"resource": ""
} |
q275821 | _Material._cauchy_equation | test | def _cauchy_equation(wavelength, coefficients):
'''
Helpful function to evaluate Cauchy equations.
Args:
wavelength (float, list, None): The wavelength(s) the
Cauchy equation will be evaluated at.
coefficients (list): A list of the coefficients of
... | python | {
"resource": ""
} |
q275822 | BackendUpdate.initialize | test | def initialize(self):
# pylint: disable=attribute-defined-outside-init
"""Login on backend with username and password
:return: None
"""
try:
logger.info("Authenticating...")
self.backend = Backend(self.backend_url)
self.backend.login(self.user... | python | {
"resource": ""
} |
q275823 | Backend.login | test | def login(self, username, password, generate='enabled', proxies=None):
"""
Log into the backend and get the token
generate parameter may have following values:
- enabled: require current token (default)
- force: force new token generation
- disabled
if login is:... | python | {
"resource": ""
} |
q275824 | Backend.get_domains | test | def get_domains(self):
"""
Connect to alignak backend and retrieve all available child endpoints of root
If connection is successful, returns a list of all the resources available in the backend:
Each resource is identified with its title and provides its endpoint relative to backend
... | python | {
"resource": ""
} |
q275825 | Backend.get_all | test | def get_all(self, endpoint, params=None):
# pylint: disable=too-many-locals
"""
Get all items in the specified endpoint of alignak backend
If an error occurs, a BackendException is raised.
If the max_results parameter is not specified in parameters, it is set to
BACKEND... | python | {
"resource": ""
} |
q275826 | Backend.patch | test | def patch(self, endpoint, data, headers=None, inception=False):
"""
Method to update an item
The headers must include an If-Match containing the object _etag.
headers = {'If-Match': contact_etag}
The data dictionary contain the fields that must be modified.
If the ... | python | {
"resource": ""
} |
q275827 | Backend.delete | test | def delete(self, endpoint, headers):
"""
Method to delete an item or all items
headers['If-Match'] must contain the _etag identifier of the element to delete
:param endpoint: endpoint (API URL)
:type endpoint: str
:param headers: headers (example: Content-Type)
... | python | {
"resource": ""
} |
q275828 | samefile | test | def samefile(path1, path2):
"""
Returns True if path1 and path2 refer to the same file.
"""
# Check if both are on the same volume and have the same file ID
info1 = fs.getfileinfo(path1)
info2 = fs.getfileinfo(path2)
return (info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber and
... | python | {
"resource": ""
} |
q275829 | create | test | def create(source, link_name):
"""
Create a junction at link_name pointing to source.
"""
success = False
if not os.path.isdir(source):
raise Exception("%s is not a directory" % source)
if os.path.exists(link_name):
raise Exception("%s: junction link name already exists" % link_n... | python | {
"resource": ""
} |
q275830 | initialize_logger | test | def initialize_logger(args):
"""Sets command name and formatting for subsequent calls to logger"""
global log_filename
log_filename = os.path.join(os.getcwd(), "jacquard.log")
if args.log_file:
_validate_log_file(args.log_file)
log_filename = args.log_file
logging.basicConfig(forma... | python | {
"resource": ""
} |
q275831 | _JacquardArgumentParser.error | test | def error(self, message):
'''Suppress default exit behavior'''
message = self._remessage_invalid_subparser(message)
raise utils.UsageError(message) | python | {
"resource": ""
} |
q275832 | Mutect.claim | test | def claim(self, file_readers):
"""Recognizes and claims MuTect VCFs form the set of all input VCFs.
Each defined caller has a chance to evaluate and claim all the incoming
files as something that it can process.
Args:
file_readers: the collection of currently unclaimed file... | python | {
"resource": ""
} |
q275833 | Mutect._get_new_column_header | test | def _get_new_column_header(self, vcf_reader):
"""Returns a standardized column header.
MuTect sample headers include the name of input alignment, which is
nice, but doesn't match up with the sample names reported in Strelka
or VarScan. To fix this, we replace with NORMAL and TUMOR using... | python | {
"resource": ""
} |
q275834 | Varscan.claim | test | def claim(self, file_readers):
"""Recognizes and claims VarScan VCFs form the set of all input VCFs.
Each defined caller has a chance to evaluate and claim all the incoming
files as something that it can process. Since VarScan can claim
high-confidence files as well, this process is sig... | python | {
"resource": ""
} |
q275835 | _ZScoreTag._init_population_stats | test | def _init_population_stats(self, vcf_reader, dependent_tag_id):
'''Derive mean and stdev.
Adapted from online variance algorithm from Knuth, The Art of Computer
Programming, volume 2
Returns: mean and stdev when len(values) > 1, otherwise (None, None)
Values rounded to _MA... | python | {
"resource": ""
} |
q275836 | VariantCallerFactory.claim | test | def claim(self, unclaimed_file_readers):
"""Allows each caller to claim incoming files as they are recognized.
Args:
unclaimed_file_readers: Usually, all files in the input dir.
Returns:
A tuple of unclaimed file readers and claimed VcfReaders. The
presence ... | python | {
"resource": ""
} |
q275837 | Tailer.splitlines | test | def splitlines(self, data):
"""
Split data into lines where lines are separated by LINE_TERMINATORS.
:param data: Any chunk of binary data.
:return: List of lines without any characters at LINE_TERMINATORS.
"""
return re.split(b'|'.join(self.LINE_TERMINATORS), data) | python | {
"resource": ""
} |
q275838 | Tailer.prefix_line_terminator | test | def prefix_line_terminator(self, data):
"""
Return line terminator data begins with or None.
"""
for t in self.LINE_TERMINATORS:
if data.startswith(t):
return t
return None | python | {
"resource": ""
} |
q275839 | Tailer.suffix_line_terminator | test | def suffix_line_terminator(self, data):
"""
Return line terminator data ends with or None.
"""
for t in self.LINE_TERMINATORS:
if data.endswith(t):
return t
return None | python | {
"resource": ""
} |
q275840 | Tailer.seek_next_line | test | def seek_next_line(self):
"""
Seek next line relative to the current file position.
:return: Position of the line or -1 if next line was not found.
"""
where = self.file.tell()
offset = 0
while True:
data_len, data = self.read(self.read_size)
... | python | {
"resource": ""
} |
q275841 | Tailer.seek_previous_line | test | def seek_previous_line(self):
"""
Seek previous line relative to the current file position.
:return: Position of the line or -1 if previous line was not found.
"""
where = self.file.tell()
offset = 0
while True:
if offset == where:
br... | python | {
"resource": ""
} |
q275842 | Tailer.tail | test | def tail(self, lines=10):
"""
Return the last lines of the file.
"""
self.file.seek(0, SEEK_END)
for i in range(lines):
if self.seek_previous_line() == -1:
break
data = self.file.read()
for t in self.LINE_TERMINATORS:
if ... | python | {
"resource": ""
} |
q275843 | Tailer.head | test | def head(self, lines=10):
"""
Return the top lines of the file.
"""
self.file.seek(0)
for i in range(lines):
if self.seek_next_line() == -1:
break
end_pos = self.file.tell()
self.file.seek(0)
data = self.file.read... | python | {
"resource": ""
} |
q275844 | Tailer.follow | test | def follow(self):
"""
Iterator generator that returns lines as data is added to the file.
None will be yielded if no new line is available.
Caller may either wait and re-try or end iteration.
"""
trailing = True
while True:
where = sel... | python | {
"resource": ""
} |
q275845 | Strelka.claim | test | def claim(self, file_readers):
"""Recognizes and claims Strelka VCFs form the set of all input VCFs.
Each defined caller has a chance to evaluate and claim all the incoming
files as something that it can process.
Args:
file_readers: the collection of currently unclaimed fil... | python | {
"resource": ""
} |
q275846 | VcfRecord.parse_record | test | def parse_record(cls, vcf_line, sample_names):
"""Alternative constructor that parses VcfRecord from VCF string.
Aspire to parse/represent the data such that it could be reliably
round-tripped. (This nicety means INFO fields and FORMAT tags should be
treated as ordered to avoid shufflin... | python | {
"resource": ""
} |
q275847 | VcfRecord._sample_tag_values | test | def _sample_tag_values(cls, sample_names, rformat, sample_fields):
"""Creates a sample dict of tag-value dicts for a single variant record.
Args:
sample_names: list of sample name strings.
rformat: record format string (from VCF record).
sample_fields: list of string... | python | {
"resource": ""
} |
q275848 | VcfRecord.format_tags | test | def format_tags(self):
"""Returns set of format tags."""
tags = VcfRecord._EMPTY_SET
if self.sample_tag_values:
first_sample = list(self.sample_tag_values.keys())[0]
tags = set(self.sample_tag_values[first_sample].keys())
return tags | python | {
"resource": ""
} |
q275849 | VcfRecord._join_info_fields | test | def _join_info_fields(self):
"""Updates info attribute from info dict."""
if self.info_dict:
info_fields = []
if len(self.info_dict) > 1:
self.info_dict.pop(".", None)
for field, value in self.info_dict.items():
if field == value:
... | python | {
"resource": ""
} |
q275850 | VcfRecord._format_field | test | def _format_field(self):
"""Returns string representation of format field."""
format_field = "."
if self.sample_tag_values:
first_sample = list(self.sample_tag_values.keys())[0]
tag_names = self.sample_tag_values[first_sample].keys()
if tag_names:
... | python | {
"resource": ""
} |
q275851 | VcfRecord._sample_field | test | def _sample_field(self, sample):
"""Returns string representation of sample-format values.
Raises:
KeyError: if requested sample is not defined.
"""
tag_values = self.sample_tag_values[sample].values()
if tag_values:
return ":".join(tag_values)
el... | python | {
"resource": ""
} |
q275852 | VcfRecord.text | test | def text(self):
"Returns tab-delimited, newline terminated string of VcfRecord."
stringifier = [self.chrom, self.pos, self.vcf_id, self.ref, self.alt,
self.qual, self.filter, self.info,
self._format_field()]
for sample in self.sample_tag_values:
... | python | {
"resource": ""
} |
q275853 | VcfRecord.add_sample_tag_value | test | def add_sample_tag_value(self, tag_name, new_sample_values):
"""Appends a new format tag-value for all samples.
Args:
tag_name: string tag name; must not already exist
new_sample
Raises:
KeyError: if tag_name to be added already exists
"""
if... | python | {
"resource": ""
} |
q275854 | VcfRecord.add_or_replace_filter | test | def add_or_replace_filter(self, new_filter):
"""Replaces null or blank filter or adds filter to existing list."""
if self.filter.lower() in self._FILTERS_TO_REPLACE:
self.filter = new_filter
elif new_filter not in self.filter.split(";"):
self.filter = ";".join([self.filte... | python | {
"resource": ""
} |
q275855 | CategoryController.available_categories | test | def available_categories(cls, user, products=AllProducts):
''' Returns the categories available to the user. Specify `products` if
you want to restrict to just the categories that hold the specified
products, otherwise it'll do all. '''
# STOPGAP -- this needs to be elsewhere tbqh
... | python | {
"resource": ""
} |
q275856 | ProductsForm | test | def ProductsForm(category, products):
''' Produces an appropriate _ProductsForm subclass for the given render
type. '''
# Each Category.RENDER_TYPE value has a subclass here.
cat = inventory.Category
RENDER_TYPES = {
cat.RENDER_TYPE_QUANTITY: _QuantityBoxProductsForm,
cat.RENDER_TYP... | python | {
"resource": ""
} |
q275857 | staff_products_form_factory | test | def staff_products_form_factory(user):
''' Creates a StaffProductsForm that restricts the available products to
those that are available to a user. '''
products = inventory.Product.objects.all()
products = ProductController.available_products(user, products=products)
product_ids = [product.id for ... | python | {
"resource": ""
} |
q275858 | _HasProductsFields.add_product_error | test | def add_product_error(self, product, error):
''' Adds an error to the given product's field '''
''' if product in field_names:
field = field_names[product]
elif isinstance(product, inventory.Product):
return
else:
field = None '''
self.add_er... | python | {
"resource": ""
} |
q275859 | BatchController.memoise | test | def memoise(cls, func):
''' Decorator that stores the result of the stored function in the
user's results cache until the batch completes. Keyword arguments are
not yet supported.
Arguments:
func (callable(*a)): The function whose results we want
to store. Th... | python | {
"resource": ""
} |
q275860 | model_fields_form_factory | test | def model_fields_form_factory(model):
''' Creates a form for specifying fields from a model to display. '''
fields = model._meta.get_fields()
choices = []
for field in fields:
if hasattr(field, "verbose_name"):
choices.append((field.name, field.verbose_name))
class ModelFields... | python | {
"resource": ""
} |
q275861 | ItemController.items_pending_or_purchased | test | def items_pending_or_purchased(self):
''' Returns the items that this user has purchased or has pending. '''
status = [commerce.Cart.STATUS_PAID, commerce.Cart.STATUS_ACTIVE]
return self._items(status) | python | {
"resource": ""
} |
q275862 | Sender.send_email | test | def send_email(self, to, kind, **kwargs):
''' Sends an e-mail to the given address.
to: The address
kind: the ID for an e-mail kind; it should point to a subdirectory of
self.template_prefix containing subject.txt and message.html, which
are django templates for the subj... | python | {
"resource": ""
} |
q275863 | iter_osm_stream | test | def iter_osm_stream(start_sqn=None, base_url='https://planet.openstreetmap.org/replication/minute', expected_interval=60, parse_timestamps=True, state_dir=None):
"""Start processing an OSM diff stream and yield one changeset at a time to
the caller."""
# If the user specifies a state_dir, read the state fr... | python | {
"resource": ""
} |
q275864 | parse_osm_file | test | def parse_osm_file(f, parse_timestamps=True):
"""Parse a file-like containing OSM XML into memory and return an object with
the nodes, ways, and relations it contains. """
nodes = []
ways = []
relations = []
for p in iter_osm_file(f, parse_timestamps):
if type(p) == model.Node:
... | python | {
"resource": ""
} |
q275865 | iter_osm_notes | test | def iter_osm_notes(feed_limit=25, interval=60, parse_timestamps=True):
""" Parses the global OSM Notes feed and yields as much Note information as possible. """
last_seen_guid = None
while True:
u = urllib2.urlopen('https://www.openstreetmap.org/api/0.6/notes/feed?limit=%d' % feed_limit)
t... | python | {
"resource": ""
} |
q275866 | ConditionController.passes_filter | test | def passes_filter(self, user):
''' Returns true if the condition passes the filter '''
cls = type(self.condition)
qs = cls.objects.filter(pk=self.condition.id)
return self.condition in self.pre_filter(qs, user) | python | {
"resource": ""
} |
q275867 | IsMetByFilter.is_met | test | def is_met(self, user, filtered=False):
''' Returns True if this flag condition is met, otherwise returns
False. It determines if the condition is met by calling pre_filter
with a queryset containing only self.condition. '''
if filtered:
return True # Why query again?
... | python | {
"resource": ""
} |
q275868 | RemainderSetByFilter.user_quantity_remaining | test | def user_quantity_remaining(self, user, filtered=True):
''' returns 0 if the date range is violated, otherwise, it will return
the quantity remaining under the stock limit.
The filter for this condition must add an annotation called "remainder"
in order for this to work.
'''
... | python | {
"resource": ""
} |
q275869 | CategoryConditionController.pre_filter | test | def pre_filter(self, queryset, user):
''' Returns all of the items from queryset where the user has a
product from a category invoking that item's condition in one of their
carts. '''
in_user_carts = Q(
enabling_category__product__productitem__cart__user=user
)
... | python | {
"resource": ""
} |
q275870 | ProductConditionController.pre_filter | test | def pre_filter(self, queryset, user):
''' Returns all of the items from queryset where the user has a
product invoking that item's condition in one of their carts. '''
in_user_carts = Q(enabling_products__productitem__cart__user=user)
released = commerce.Cart.STATUS_RELEASED
pai... | python | {
"resource": ""
} |
q275871 | TimeOrStockLimitConditionController.pre_filter | test | def pre_filter(self, queryset, user):
''' Returns all of the items from queryset where the date falls into
any specified range, but not yet where the stock limit is not yet
reached.'''
now = timezone.now()
# Keep items with no start time, or start time not yet met.
quer... | python | {
"resource": ""
} |
q275872 | SpeakerConditionController.pre_filter | test | def pre_filter(self, queryset, user):
''' Returns all of the items from queryset which are enabled by a user
being a presenter or copresenter of a non-cancelled proposal. '''
# Filter out cancelled proposals
queryset = queryset.filter(
proposal_kind__proposalbase__presentati... | python | {
"resource": ""
} |
q275873 | GroupMemberConditionController.pre_filter | test | def pre_filter(self, conditions, user):
''' Returns all of the items from conditions which are enabled by a
user being member of a Django Auth Group. '''
return conditions.filter(group__in=user.groups.all()) | python | {
"resource": ""
} |
q275874 | _modifies_cart | test | def _modifies_cart(func):
''' Decorator that makes the wrapped function raise ValidationError
if we're doing something that could modify the cart.
It also wraps the execution of this function in a database transaction,
and marks the boundaries of a cart operations batch.
'''
@functools.wraps(f... | python | {
"resource": ""
} |
q275875 | CartController.for_user | test | def for_user(cls, user):
''' Returns the user's current cart, or creates a new cart
if there isn't one ready yet. '''
try:
existing = commerce.Cart.objects.get(
user=user,
status=commerce.Cart.STATUS_ACTIVE,
)
except ObjectDoesNotE... | python | {
"resource": ""
} |
q275876 | CartController._autoextend_reservation | test | def _autoextend_reservation(self):
''' Updates the cart's time last updated value, which is used to
determine whether the cart has reserved the items and discounts it
holds. '''
time = timezone.now()
# Calculate the residual of the _old_ reservation duration
# if it's g... | python | {
"resource": ""
} |
q275877 | CartController.apply_voucher | test | def apply_voucher(self, voucher_code):
''' Applies the voucher with the given code to this cart. '''
# Try and find the voucher
voucher = inventory.Voucher.objects.get(code=voucher_code.upper())
# Re-applying vouchers should be idempotent
if voucher in self.cart.vouchers.all():... | python | {
"resource": ""
} |
q275878 | CartController.validate_cart | test | def validate_cart(self):
''' Determines whether the status of the current cart is valid;
this is normally called before generating or paying an invoice '''
cart = self.cart
user = self.cart.user
errors = []
try:
self._test_vouchers(self.cart.vouchers.all())
... | python | {
"resource": ""
} |
q275879 | CartController.fix_simple_errors | test | def fix_simple_errors(self):
''' This attempts to fix the easy errors raised by ValidationError.
This includes removing items from the cart that are no longer
available, recalculating all of the discounts, and removing voucher
codes that are no longer available. '''
# Fix vouche... | python | {
"resource": ""
} |
q275880 | CartController._recalculate_discounts | test | def _recalculate_discounts(self):
''' Calculates all of the discounts available for this product.'''
# Delete the existing entries.
commerce.DiscountItem.objects.filter(cart=self.cart).delete()
# Order the products such that the most expensive ones are
# processed first.
... | python | {
"resource": ""
} |
q275881 | CartController._add_discount | test | def _add_discount(self, product, quantity, discounts):
''' Applies the best discounts on the given product, from the given
discounts.'''
def matches(discount):
''' Returns True if and only if the given discount apples to
our product. '''
if isinstance(discoun... | python | {
"resource": ""
} |
q275882 | report_view | test | def report_view(title, form_type=None):
''' Decorator that converts a report view function into something that
displays a Report.
Arguments:
title (str):
The title of the report.
form_type (Optional[forms.Form]):
A form class that can make this report display things.... | python | {
"resource": ""
} |
q275883 | ListReport.rows | test | def rows(self, content_type):
''' Returns the data rows for the table. '''
for row in self._data:
yield [
self.cell_text(content_type, i, cell)
for i, cell in enumerate(row)
] | python | {
"resource": ""
} |
q275884 | ReportView.get_form | test | def get_form(self, request):
''' Creates an instance of self.form_type using request.GET '''
# Create a form instance
if self.form_type is not None:
form = self.form_type(request.GET)
# Pre-validate it
form.is_valid()
else:
form = None
... | python | {
"resource": ""
} |
q275885 | ReportView.render | test | def render(self, data):
''' Renders the reports based on data.content_type's value.
Arguments:
data (ReportViewRequestData): The report data. data.content_type
is used to determine how the reports are rendered.
Returns:
HTTPResponse: The rendered version... | python | {
"resource": ""
} |
q275886 | reports_list | test | def reports_list(request):
''' Lists all of the reports currently available. '''
reports = []
for report in get_all_reports():
reports.append({
"name": report.__name__,
"url": reverse(report),
"description": report.__doc__,
})
reports.sort(key=lambd... | python | {
"resource": ""
} |
q275887 | items_sold | test | def items_sold():
''' Summarises the items sold and discounts granted for a given set of
products, or products from categories. '''
data = None
headings = None
line_items = commerce.LineItem.objects.filter(
invoice__status=commerce.Invoice.STATUS_PAID,
).select_related("invoice")
... | python | {
"resource": ""
} |
q275888 | sales_payment_summary | test | def sales_payment_summary():
''' Summarises paid items and payments. '''
def value_or_zero(aggregate, key):
return aggregate[key] or 0
def sum_amount(payment_set):
a = payment_set.values("amount").aggregate(total=Sum("amount"))
return value_or_zero(a, "total")
headings = ["Cat... | python | {
"resource": ""
} |
q275889 | payments | test | def payments():
''' Shows the history of payments into the system '''
payments = commerce.PaymentBase.objects.all()
return QuerysetReport(
"Payments",
["invoice__id", "id", "reference", "amount"],
payments,
link_view=views.invoice,
) | python | {
"resource": ""
} |
q275890 | credit_note_refunds | test | def credit_note_refunds():
''' Shows all of the credit notes that have been generated. '''
notes_refunded = commerce.CreditNote.refunded()
return QuerysetReport(
"Credit note refunds",
["id", "creditnoterefund__reference", "amount"],
notes_refunded,
link_view=views.credit_not... | python | {
"resource": ""
} |
q275891 | product_status | test | def product_status(request, form):
''' Summarises the inventory status of the given items, grouping by
invoice status. '''
products = form.cleaned_data["product"]
categories = form.cleaned_data["category"]
items = commerce.ProductItem.objects.filter(
Q(product__in=products) | Q(product__ca... | python | {
"resource": ""
} |
q275892 | discount_status | test | def discount_status(request, form):
''' Summarises the usage of a given discount. '''
discounts = form.cleaned_data["discount"]
items = commerce.DiscountItem.objects.filter(
Q(discount__in=discounts),
).select_related("cart", "product", "product__category")
items = group_by_cart_status(
... | python | {
"resource": ""
} |
q275893 | product_line_items | test | def product_line_items(request, form):
''' Shows each product line item from invoices, including their date and
purchashing customer. '''
products = form.cleaned_data["product"]
categories = form.cleaned_data["category"]
invoices = commerce.Invoice.objects.filter(
(
Q(lineitem_... | python | {
"resource": ""
} |
q275894 | paid_invoices_by_date | test | def paid_invoices_by_date(request, form):
''' Shows the number of paid invoices containing given products or
categories per day. '''
products = form.cleaned_data["product"]
categories = form.cleaned_data["category"]
invoices = commerce.Invoice.objects.filter(
(
Q(lineitem__prod... | python | {
"resource": ""
} |
q275895 | credit_notes | test | def credit_notes(request, form):
''' Shows all of the credit notes in the system. '''
notes = commerce.CreditNote.objects.all().select_related(
"creditnoterefund",
"creditnoteapplication",
"invoice",
"invoice__user__attendee__attendeeprofilebase",
)
return QuerysetRepor... | python | {
"resource": ""
} |
q275896 | invoices | test | def invoices(request, form):
''' Shows all of the invoices in the system. '''
invoices = commerce.Invoice.objects.all().order_by("status", "id")
return QuerysetReport(
"Invoices",
["id", "recipient", "value", "get_status_display"],
invoices,
headings=["id", "Recipient", "Va... | python | {
"resource": ""
} |
q275897 | attendee_list | test | def attendee_list(request):
''' Returns a list of all attendees. '''
attendees = people.Attendee.objects.select_related(
"attendeeprofilebase",
"user",
)
profiles = AttendeeProfile.objects.filter(
attendee__in=attendees
).select_related(
"attendee", "attendee__user"... | python | {
"resource": ""
} |
q275898 | speaker_registrations | test | def speaker_registrations(request, form):
''' Shows registration status for speakers with a given proposal kind. '''
kinds = form.cleaned_data["kind"]
presentations = schedule_models.Presentation.objects.filter(
proposal_base__kind__in=kinds,
).exclude(
cancelled=True,
)
users... | python | {
"resource": ""
} |
q275899 | manifest | test | def manifest(request, form):
'''
Produces the registration manifest for people with the given product
type.
'''
products = form.cleaned_data["product"]
categories = form.cleaned_data["category"]
line_items = (
Q(lineitem__product__in=products) |
Q(lineitem__product__categor... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.