_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q275900
|
missing_categories
|
test
|
def missing_categories(context):
''' Adds the categories that the user does not currently have. '''
user = user_for_context(context)
categories_available = set(CategoryController.available_categories(user))
items = ItemController(user).items_pending_or_purchased()
categories_held = set()
for product, quantity in items:
categories_held.add(product.category)
return categories_available - categories_held
|
python
|
{
"resource": ""
}
|
q275901
|
available_credit
|
test
|
def available_credit(context):
''' Calculates the sum of unclaimed credit from this user's credit notes.
Returns:
Decimal: the sum of the values of unclaimed credit notes for the
current user.
'''
notes = commerce.CreditNote.unclaimed().filter(
invoice__user=user_for_context(context),
)
ret = notes.values("amount").aggregate(Sum("amount"))["amount__sum"] or 0
return 0 - ret
|
python
|
{
"resource": ""
}
|
q275902
|
sold_out_and_unregistered
|
test
|
def sold_out_and_unregistered(context):
''' If the current user is unregistered, returns True if there are no
products in the TICKET_PRODUCT_CATEGORY that are available to that user.
If there *are* products available, the return False.
If the current user *is* registered, then return None (it's not a
pertinent question for people who already have a ticket).
'''
user = user_for_context(context)
if hasattr(user, "attendee") and user.attendee.completed_registration:
# This user has completed registration, and so we don't need to answer
# whether they have sold out yet.
# TODO: what if a user has got to the review phase?
# currently that user will hit the review page, click "Check out and
# pay", and that will fail. Probably good enough for now.
return None
ticket_category = settings.TICKET_PRODUCT_CATEGORY
categories = available_categories(context)
return ticket_category not in [cat.id for cat in categories]
|
python
|
{
"resource": ""
}
|
q275903
|
guided_registration
|
test
|
def guided_registration(request, page_number=None):
''' Goes through the registration process in order, making sure user sees
all valid categories.
The user must be logged in to see this view.
Parameter:
page_number:
1) Profile form (and e-mail address?)
2) Ticket type
3) Remaining products
4) Mark registration as complete
Returns:
render: Renders ``registrasion/guided_registration.html``,
with the following data::
{
"current_step": int(), # The current step in the
# registration
"sections": sections, # A list of
# GuidedRegistrationSections
"title": str(), # The title of the page
"total_steps": int(), # The total number of steps
}
'''
PAGE_PROFILE = 1
PAGE_TICKET = 2
PAGE_PRODUCTS = 3
PAGE_PRODUCTS_MAX = 4
TOTAL_PAGES = 4
ticket_category = inventory.Category.objects.get(
id=settings.TICKET_PRODUCT_CATEGORY
)
cart = CartController.for_user(request.user)
attendee = people.Attendee.get_instance(request.user)
# This guided registration process is only for people who have
# not completed registration (and has confusing behaviour if you go
# back to it.)
if attendee.completed_registration:
return redirect(review)
# Calculate the current maximum page number for this user.
has_profile = hasattr(attendee, "attendeeprofilebase")
if not has_profile:
# If there's no profile, they have to go to the profile page.
max_page = PAGE_PROFILE
redirect_page = PAGE_PROFILE
else:
# We have a profile.
# Do they have a ticket?
products = inventory.Product.objects.filter(
productitem__cart=cart.cart
)
products = products.filter(category=ticket_category)
if products.count() == 0:
# If no ticket, they can only see the profile or ticket page.
max_page = PAGE_TICKET
redirect_page = PAGE_TICKET
else:
# If there's a ticket, they should *see* the general products page#
# but be able to go to the overflow page if needs be.
max_page = PAGE_PRODUCTS_MAX
redirect_page = PAGE_PRODUCTS
if page_number is None or int(page_number) > max_page:
return redirect("guided_registration", redirect_page)
page_number = int(page_number)
next_step = redirect("guided_registration", page_number + 1)
with BatchController.batch(request.user):
# This view doesn't work if the conference has sold out.
available = ProductController.available_products(
request.user, category=ticket_category
)
if not available:
messages.error(request, "There are no more tickets available.")
return redirect("dashboard")
sections = []
# Build up the list of sections
if page_number == PAGE_PROFILE:
# Profile bit
title = "Attendee information"
sections = _guided_registration_profile_and_voucher(request)
elif page_number == PAGE_TICKET:
# Select ticket
title = "Select ticket type"
sections = _guided_registration_products(
request, GUIDED_MODE_TICKETS_ONLY
)
elif page_number == PAGE_PRODUCTS:
# Select additional items
title = "Additional items"
sections = _guided_registration_products(
request, GUIDED_MODE_ALL_ADDITIONAL
)
elif page_number == PAGE_PRODUCTS_MAX:
# Items enabled by things on page 3 -- only shows things
# that have not been marked as complete.
title = "More additional items"
sections = _guided_registration_products(
request, GUIDED_MODE_EXCLUDE_COMPLETE
)
if not sections:
# We've filled in every category
attendee.completed_registration = True
attendee.save()
return redirect("review")
if sections and request.method == "POST":
for section in sections:
if section.form.errors:
break
else:
# We've successfully processed everything
return next_step
data = {
"current_step": page_number,
"sections": sections,
"title": title,
"total_steps": TOTAL_PAGES,
}
return render(request, "registrasion/guided_registration.html", data)
|
python
|
{
"resource": ""
}
|
q275904
|
edit_profile
|
test
|
def edit_profile(request):
''' View for editing an attendee's profile
The user must be logged in to edit their profile.
Returns:
redirect or render:
In the case of a ``POST`` request, it'll redirect to ``dashboard``,
or otherwise, it will render ``registrasion/profile_form.html``
with data::
{
"form": form, # Instance of ATTENDEE_PROFILE_FORM.
}
'''
form, handled = _handle_profile(request, "profile")
if handled and not form.errors:
messages.success(
request,
"Your attendee profile was updated.",
)
return redirect("dashboard")
data = {
"form": form,
}
return render(request, "registrasion/profile_form.html", data)
|
python
|
{
"resource": ""
}
|
q275905
|
_handle_profile
|
test
|
def _handle_profile(request, prefix):
''' Returns a profile form instance, and a boolean which is true if the
form was handled. '''
attendee = people.Attendee.get_instance(request.user)
try:
profile = attendee.attendeeprofilebase
profile = people.AttendeeProfileBase.objects.get_subclass(
pk=profile.id,
)
except ObjectDoesNotExist:
profile = None
# Load a pre-entered name from the speaker's profile,
# if they have one.
try:
speaker_profile = request.user.speaker_profile
speaker_name = speaker_profile.name
except ObjectDoesNotExist:
speaker_name = None
name_field = ProfileForm.Meta.model.name_field()
initial = {}
if profile is None and name_field is not None:
initial[name_field] = speaker_name
form = ProfileForm(
request.POST or None,
initial=initial,
instance=profile,
prefix=prefix
)
handled = True if request.POST else False
if request.POST and form.is_valid():
form.instance.attendee = attendee
form.save()
return form, handled
|
python
|
{
"resource": ""
}
|
q275906
|
product_category
|
test
|
def product_category(request, category_id):
''' Form for selecting products from an individual product category.
Arguments:
category_id (castable to int): The id of the category to display.
Returns:
redirect or render:
If the form has been sucessfully submitted, redirect to
``dashboard``. Otherwise, render
``registrasion/product_category.html`` with data::
{
"category": category, # An inventory.Category for
# category_id
"discounts": discounts, # A list of
# DiscountAndQuantity
"form": products_form, # A form for selecting
# products
"voucher_form": voucher_form, # A form for entering a
# voucher code
}
'''
PRODUCTS_FORM_PREFIX = "products"
VOUCHERS_FORM_PREFIX = "vouchers"
# Handle the voucher form *before* listing products.
# Products can change as vouchers are entered.
v = _handle_voucher(request, VOUCHERS_FORM_PREFIX)
voucher_form, voucher_handled = v
category_id = int(category_id) # Routing is [0-9]+
category = inventory.Category.objects.get(pk=category_id)
with BatchController.batch(request.user):
products = ProductController.available_products(
request.user,
category=category,
)
if not products:
messages.warning(
request,
(
"There are no products available from category: " +
category.name
),
)
return redirect("dashboard")
p = _handle_products(request, category, products, PRODUCTS_FORM_PREFIX)
products_form, discounts, products_handled = p
if request.POST and not voucher_handled and not products_form.errors:
# Only return to the dashboard if we didn't add a voucher code
# and if there's no errors in the products form
if products_form.has_changed():
messages.success(
request,
"Your reservations have been updated.",
)
return redirect(review)
data = {
"category": category,
"discounts": discounts,
"form": products_form,
"voucher_form": voucher_form,
}
return render(request, "registrasion/product_category.html", data)
|
python
|
{
"resource": ""
}
|
q275907
|
_handle_products
|
test
|
def _handle_products(request, category, products, prefix):
''' Handles a products list form in the given request. Returns the
form instance, the discounts applicable to this form, and whether the
contents were handled. '''
current_cart = CartController.for_user(request.user)
ProductsForm = forms.ProductsForm(category, products)
# Create initial data for each of products in category
items = commerce.ProductItem.objects.filter(
product__in=products,
cart=current_cart.cart,
).select_related("product")
quantities = []
seen = set()
for item in items:
quantities.append((item.product, item.quantity))
seen.add(item.product)
zeros = set(products) - seen
for product in zeros:
quantities.append((product, 0))
products_form = ProductsForm(
request.POST or None,
product_quantities=quantities,
prefix=prefix,
)
if request.method == "POST" and products_form.is_valid():
if products_form.has_changed():
_set_quantities_from_products_form(products_form, current_cart)
# If category is required, the user must have at least one
# in an active+valid cart
if category.required:
carts = commerce.Cart.objects.filter(user=request.user)
items = commerce.ProductItem.objects.filter(
product__category=category,
cart=carts,
)
if len(items) == 0:
products_form.add_error(
None,
"You must have at least one item from this category",
)
handled = False if products_form.errors else True
# Making this a function to lazily evaluate when it's displayed
# in templates.
discounts = util.lazy(
DiscountController.available_discounts,
request.user,
[],
products,
)
return products_form, discounts, handled
|
python
|
{
"resource": ""
}
|
q275908
|
_handle_voucher
|
test
|
def _handle_voucher(request, prefix):
''' Handles a voucher form in the given request. Returns the voucher
form instance, and whether the voucher code was handled. '''
voucher_form = forms.VoucherForm(request.POST or None, prefix=prefix)
current_cart = CartController.for_user(request.user)
if (voucher_form.is_valid() and
voucher_form.cleaned_data["voucher"].strip()):
voucher = voucher_form.cleaned_data["voucher"]
voucher = inventory.Voucher.normalise_code(voucher)
if len(current_cart.cart.vouchers.filter(code=voucher)) > 0:
# This voucher has already been applied to this cart.
# Do not apply code
handled = False
else:
try:
current_cart.apply_voucher(voucher)
except Exception as e:
voucher_form.add_error("voucher", e)
handled = True
else:
handled = False
return (voucher_form, handled)
|
python
|
{
"resource": ""
}
|
q275909
|
checkout
|
test
|
def checkout(request, user_id=None):
''' Runs the checkout process for the current cart.
If the query string contains ``fix_errors=true``, Registrasion will attempt
to fix errors preventing the system from checking out, including by
cancelling expired discounts and vouchers, and removing any unavailable
products.
Arguments:
user_id (castable to int):
If the requesting user is staff, then the user ID can be used to
run checkout for another user.
Returns:
render or redirect:
If the invoice is generated successfully, or there's already a
valid invoice for the current cart, redirect to ``invoice``.
If there are errors when generating the invoice, render
``registrasion/checkout_errors.html`` with the following data::
{
"error_list", [str, ...] # The errors to display.
}
'''
if user_id is not None:
if request.user.is_staff:
user = User.objects.get(id=int(user_id))
else:
raise Http404()
else:
user = request.user
current_cart = CartController.for_user(user)
if "fix_errors" in request.GET and request.GET["fix_errors"] == "true":
current_cart.fix_simple_errors()
try:
current_invoice = InvoiceController.for_cart(current_cart.cart)
except ValidationError as ve:
return _checkout_errors(request, ve)
return redirect("invoice", current_invoice.invoice.id)
|
python
|
{
"resource": ""
}
|
q275910
|
invoice_access
|
test
|
def invoice_access(request, access_code):
''' Redirects to an invoice for the attendee that matches the given access
code, if any.
If the attendee has multiple invoices, we use the following tie-break:
- If there's an unpaid invoice, show that, otherwise
- If there's a paid invoice, show the most recent one, otherwise
- Show the most recent invoid of all
Arguments:
access_code (castable to int): The access code for the user whose
invoice you want to see.
Returns:
redirect:
Redirect to the selected invoice for that user.
Raises:
Http404: If the user has no invoices.
'''
invoices = commerce.Invoice.objects.filter(
user__attendee__access_code=access_code,
).order_by("-issue_time")
if not invoices:
raise Http404()
unpaid = invoices.filter(status=commerce.Invoice.STATUS_UNPAID)
paid = invoices.filter(status=commerce.Invoice.STATUS_PAID)
if unpaid:
invoice = unpaid[0] # (should only be 1 unpaid invoice?)
elif paid:
invoice = paid[0] # Most recent paid invoice
else:
invoice = invoices[0] # Most recent of any invoices
return redirect("invoice", invoice.id, access_code)
|
python
|
{
"resource": ""
}
|
q275911
|
invoice
|
test
|
def invoice(request, invoice_id, access_code=None):
''' Displays an invoice.
This view is not authenticated, but it will only allow access to either:
the user the invoice belongs to; staff; or a request made with the correct
access code.
Arguments:
invoice_id (castable to int): The invoice_id for the invoice you want
to view.
access_code (Optional[str]): The access code for the user who owns
this invoice.
Returns:
render:
Renders ``registrasion/invoice.html``, with the following
data::
{
"invoice": models.commerce.Invoice(),
}
Raises:
Http404: if the current user cannot view this invoice and the correct
access_code is not provided.
'''
current_invoice = InvoiceController.for_id_or_404(invoice_id)
if not current_invoice.can_view(
user=request.user,
access_code=access_code,
):
raise Http404()
data = {
"invoice": current_invoice.invoice,
}
return render(request, "registrasion/invoice.html", data)
|
python
|
{
"resource": ""
}
|
q275912
|
manual_payment
|
test
|
def manual_payment(request, invoice_id):
''' Allows staff to make manual payments or refunds on an invoice.
This form requires a login, and the logged in user needs to be staff.
Arguments:
invoice_id (castable to int): The invoice ID to be paid
Returns:
render:
Renders ``registrasion/manual_payment.html`` with the following
data::
{
"invoice": models.commerce.Invoice(),
"form": form, # A form that saves a ``ManualPayment``
# object.
}
'''
FORM_PREFIX = "manual_payment"
current_invoice = InvoiceController.for_id_or_404(invoice_id)
form = forms.ManualPaymentForm(
request.POST or None,
prefix=FORM_PREFIX,
)
if request.POST and form.is_valid():
form.instance.invoice = current_invoice.invoice
form.instance.entered_by = request.user
form.save()
current_invoice.update_status()
form = forms.ManualPaymentForm(prefix=FORM_PREFIX)
data = {
"invoice": current_invoice.invoice,
"form": form,
}
return render(request, "registrasion/manual_payment.html", data)
|
python
|
{
"resource": ""
}
|
q275913
|
refund
|
test
|
def refund(request, invoice_id):
''' Marks an invoice as refunded and requests a credit note for the
full amount paid against the invoice.
This view requires a login, and the logged in user must be staff.
Arguments:
invoice_id (castable to int): The ID of the invoice to refund.
Returns:
redirect:
Redirects to ``invoice``.
'''
current_invoice = InvoiceController.for_id_or_404(invoice_id)
try:
current_invoice.refund()
messages.success(request, "This invoice has been refunded.")
except ValidationError as ve:
messages.error(request, ve)
return redirect("invoice", invoice_id)
|
python
|
{
"resource": ""
}
|
q275914
|
credit_note
|
test
|
def credit_note(request, note_id, access_code=None):
''' Displays a credit note.
If ``request`` is a ``POST`` request, forms for applying or refunding
a credit note will be processed.
This view requires a login, and the logged in user must be staff.
Arguments:
note_id (castable to int): The ID of the credit note to view.
Returns:
render or redirect:
If the "apply to invoice" form is correctly processed, redirect to
that invoice, otherwise, render ``registration/credit_note.html``
with the following data::
{
"credit_note": models.commerce.CreditNote(),
"apply_form": form, # A form for applying credit note
# to an invoice.
"refund_form": form, # A form for applying a *manual*
# refund of the credit note.
"cancellation_fee_form" : form, # A form for generating an
# invoice with a
# cancellation fee
}
'''
note_id = int(note_id)
current_note = CreditNoteController.for_id_or_404(note_id)
apply_form = forms.ApplyCreditNoteForm(
current_note.credit_note.invoice.user,
request.POST or None,
prefix="apply_note"
)
refund_form = forms.ManualCreditNoteRefundForm(
request.POST or None,
prefix="refund_note"
)
cancellation_fee_form = forms.CancellationFeeForm(
request.POST or None,
prefix="cancellation_fee"
)
if request.POST and apply_form.is_valid():
inv_id = apply_form.cleaned_data["invoice"]
invoice = commerce.Invoice.objects.get(pk=inv_id)
current_note.apply_to_invoice(invoice)
messages.success(
request,
"Applied credit note %d to invoice." % note_id,
)
return redirect("invoice", invoice.id)
elif request.POST and refund_form.is_valid():
refund_form.instance.entered_by = request.user
refund_form.instance.parent = current_note.credit_note
refund_form.save()
messages.success(
request,
"Applied manual refund to credit note."
)
refund_form = forms.ManualCreditNoteRefundForm(
prefix="refund_note",
)
elif request.POST and cancellation_fee_form.is_valid():
percentage = cancellation_fee_form.cleaned_data["percentage"]
invoice = current_note.cancellation_fee(percentage)
messages.success(
request,
"Generated cancellation fee for credit note %d." % note_id,
)
return redirect("invoice", invoice.invoice.id)
data = {
"credit_note": current_note.credit_note,
"apply_form": apply_form,
"refund_form": refund_form,
"cancellation_fee_form": cancellation_fee_form,
}
return render(request, "registrasion/credit_note.html", data)
|
python
|
{
"resource": ""
}
|
q275915
|
amend_registration
|
test
|
def amend_registration(request, user_id):
''' Allows staff to amend a user's current registration cart, and etc etc.
'''
user = User.objects.get(id=int(user_id))
current_cart = CartController.for_user(user)
items = commerce.ProductItem.objects.filter(
cart=current_cart.cart,
).select_related("product")
initial = [{"product": i.product, "quantity": i.quantity} for i in items]
StaffProductsFormSet = forms.staff_products_formset_factory(user)
formset = StaffProductsFormSet(
request.POST or None,
initial=initial,
prefix="products",
)
for item, form in zip(items, formset):
queryset = inventory.Product.objects.filter(id=item.product.id)
form.fields["product"].queryset = queryset
voucher_form = forms.VoucherForm(
request.POST or None,
prefix="voucher",
)
if request.POST and formset.is_valid():
pq = [
(f.cleaned_data["product"], f.cleaned_data["quantity"])
for f in formset
if "product" in f.cleaned_data and
f.cleaned_data["product"] is not None
]
try:
current_cart.set_quantities(pq)
return redirect(amend_registration, user_id)
except ValidationError as ve:
for ve_field in ve.error_list:
product, message = ve_field.message
for form in formset:
if "product" not in form.cleaned_data:
# This is the empty form.
continue
if form.cleaned_data["product"] == product:
form.add_error("quantity", message)
if request.POST and voucher_form.has_changed() and voucher_form.is_valid():
try:
current_cart.apply_voucher(voucher_form.cleaned_data["voucher"])
return redirect(amend_registration, user_id)
except ValidationError as ve:
voucher_form.add_error(None, ve)
ic = ItemController(user)
data = {
"user": user,
"paid": ic.items_purchased(),
"cancelled": ic.items_released(),
"form": formset,
"voucher_form": voucher_form,
}
return render(request, "registrasion/amend_registration.html", data)
|
python
|
{
"resource": ""
}
|
q275916
|
extend_reservation
|
test
|
def extend_reservation(request, user_id, days=7):
''' Allows staff to extend the reservation on a given user's cart.
'''
user = User.objects.get(id=int(user_id))
cart = CartController.for_user(user)
cart.extend_reservation(datetime.timedelta(days=days))
return redirect(request.META["HTTP_REFERER"])
|
python
|
{
"resource": ""
}
|
q275917
|
invoice_mailout
|
test
|
def invoice_mailout(request):
''' Allows staff to send emails to users based on their invoice status. '''
category = request.GET.getlist("category", [])
product = request.GET.getlist("product", [])
status = request.GET.get("status")
form = forms.InvoiceEmailForm(
request.POST or None,
category=category,
product=product,
status=status,
)
emails = []
if form.is_valid():
emails = []
for invoice in form.cleaned_data["invoice"]:
# datatuple = (subject, message, from_email, recipient_list)
from_email = form.cleaned_data["from_email"]
subject = form.cleaned_data["subject"]
body = Template(form.cleaned_data["body"]).render(
Context({
"invoice": invoice,
"user": invoice.user,
})
)
recipient_list = [invoice.user.email]
emails.append(Email(subject, body, from_email, recipient_list))
if form.cleaned_data["action"] == forms.InvoiceEmailForm.ACTION_SEND:
# Send e-mails *ONLY* if we're sending.
send_mass_mail(emails)
messages.info(request, "The e-mails have been sent.")
data = {
"form": form,
"emails": emails,
}
return render(request, "registrasion/invoice_mailout.html", data)
|
python
|
{
"resource": ""
}
|
q275918
|
badges
|
test
|
def badges(request):
''' Either displays a form containing a list of users with badges to
render, or returns a .zip file containing their badges. '''
category = request.GET.getlist("category", [])
product = request.GET.getlist("product", [])
status = request.GET.get("status")
form = forms.InvoicesWithProductAndStatusForm(
request.POST or None,
category=category,
product=product,
status=status,
)
if form.is_valid():
response = HttpResponse()
response["Content-Type"] = "application.zip"
response["Content-Disposition"] = 'attachment; filename="badges.zip"'
z = zipfile.ZipFile(response, "w")
for invoice in form.cleaned_data["invoice"]:
user = invoice.user
badge = render_badge(user)
z.writestr("badge_%d.svg" % user.id, badge.encode("utf-8"))
return response
data = {
"form": form,
}
return render(request, "registrasion/badges.html", data)
|
python
|
{
"resource": ""
}
|
q275919
|
render_badge
|
test
|
def render_badge(user):
''' Renders a single user's badge. '''
data = {
"user": user,
}
t = loader.get_template('registrasion/badge.svg')
return t.render(data)
|
python
|
{
"resource": ""
}
|
q275920
|
DiscountController.available_discounts
|
test
|
def available_discounts(cls, user, categories, products):
''' Returns all discounts available to this user for the given
categories and products. The discounts also list the available quantity
for this user, not including products that are pending purchase. '''
filtered_clauses = cls._filtered_clauses(user)
# clauses that match provided categories
categories = set(categories)
# clauses that match provided products
products = set(products)
# clauses that match categories for provided products
product_categories = set(product.category for product in products)
# (Not relevant: clauses that match products in provided categories)
all_categories = categories | product_categories
filtered_clauses = (
clause for clause in filtered_clauses
if hasattr(clause, 'product') and clause.product in products or
hasattr(clause, 'category') and clause.category in all_categories
)
discounts = []
# Markers so that we don't need to evaluate given conditions
# more than once
accepted_discounts = set()
failed_discounts = set()
for clause in filtered_clauses:
discount = clause.discount
cond = ConditionController.for_condition(discount)
past_use_count = clause.past_use_count
if past_use_count >= clause.quantity:
# This clause has exceeded its use count
pass
elif discount not in failed_discounts:
# This clause is still available
is_accepted = discount in accepted_discounts
if is_accepted or cond.is_met(user, filtered=True):
# This clause is valid for this user
discounts.append(DiscountAndQuantity(
discount=discount,
clause=clause,
quantity=clause.quantity - past_use_count,
))
accepted_discounts.add(discount)
else:
# This clause is not valid for this user
failed_discounts.add(discount)
return discounts
|
python
|
{
"resource": ""
}
|
q275921
|
DiscountController._annotate_with_past_uses
|
test
|
def _annotate_with_past_uses(cls, queryset, user):
''' Annotates the queryset with a usage count for that discount claus
by the given user. '''
if queryset.model == conditions.DiscountForCategory:
matches = (
Q(category=F('discount__discountitem__product__category'))
)
elif queryset.model == conditions.DiscountForProduct:
matches = (
Q(product=F('discount__discountitem__product'))
)
in_carts = (
Q(discount__discountitem__cart__user=user) &
Q(discount__discountitem__cart__status=commerce.Cart.STATUS_PAID)
)
past_use_quantity = When(
in_carts & matches,
then="discount__discountitem__quantity",
)
past_use_quantity_or_zero = Case(
past_use_quantity,
default=Value(0),
)
queryset = queryset.annotate(
past_use_count=Sum(past_use_quantity_or_zero)
)
return queryset
|
python
|
{
"resource": ""
}
|
q275922
|
ProductController.available_products
|
test
|
def available_products(cls, user, category=None, products=None):
''' Returns a list of all of the products that are available per
flag conditions from the given categories. '''
if category is None and products is None:
raise ValueError("You must provide products or a category")
if category is not None:
all_products = inventory.Product.objects.filter(category=category)
all_products = all_products.select_related("category")
else:
all_products = []
if products is not None:
all_products = set(itertools.chain(all_products, products))
category_remainders = CategoryController.user_remainders(user)
product_remainders = ProductController.user_remainders(user)
passed_limits = set(
product
for product in all_products
if category_remainders[product.category.id] > 0
if product_remainders[product.id] > 0
)
failed_and_messages = FlagController.test_flags(
user, products=passed_limits
)
failed_conditions = set(i[0] for i in failed_and_messages)
out = list(passed_limits - failed_conditions)
out.sort(key=lambda product: product.order)
return out
|
python
|
{
"resource": ""
}
|
q275923
|
CreditNoteController.apply_to_invoice
|
test
|
def apply_to_invoice(self, invoice):
''' Applies the total value of this credit note to the specified
invoice. If this credit note overpays the invoice, a new credit note
containing the residual value will be created.
Raises ValidationError if the given invoice is not allowed to be
paid.
'''
# Local import to fix import cycles. Can we do better?
from .invoice import InvoiceController
inv = InvoiceController(invoice)
inv.validate_allowed_to_pay()
# Apply payment to invoice
commerce.CreditNoteApplication.objects.create(
parent=self.credit_note,
invoice=invoice,
amount=self.credit_note.value,
reference="Applied credit note #%d" % self.credit_note.id,
)
inv.update_status()
|
python
|
{
"resource": ""
}
|
q275924
|
CreditNoteController.cancellation_fee
|
test
|
def cancellation_fee(self, percentage):
''' Generates an invoice with a cancellation fee, and applies
credit to the invoice.
percentage (Decimal): The percentage of the credit note to turn into
a cancellation fee. Must be 0 <= percentage <= 100.
'''
# Local import to fix import cycles. Can we do better?
from .invoice import InvoiceController
assert(percentage >= 0 and percentage <= 100)
cancellation_fee = self.credit_note.value * percentage / 100
due = datetime.timedelta(days=1)
item = [("Cancellation fee", cancellation_fee)]
invoice = InvoiceController.manual_invoice(
self.credit_note.invoice.user, due, item
)
if not invoice.is_paid:
self.apply_to_invoice(invoice)
return InvoiceController(invoice)
|
python
|
{
"resource": ""
}
|
q275925
|
generate_access_code
|
test
|
def generate_access_code():
''' Generates an access code for users' payments as well as their
fulfilment code for check-in.
The access code will 4 characters long, which allows for 1,500,625
unique codes, which really should be enough for anyone. '''
length = 6
# all upper-case letters + digits 1-9 (no 0 vs O confusion)
chars = string.uppercase + string.digits[1:]
# 6 chars => 35 ** 6 = 1838265625 (should be enough for anyone)
return get_random_string(length=length, allowed_chars=chars)
|
python
|
{
"resource": ""
}
|
q275926
|
lazy
|
test
|
def lazy(function, *args, **kwargs):
''' Produces a callable so that functions can be lazily evaluated in
templates.
Arguments:
function (callable): The function to call at evaluation time.
args: Positional arguments, passed directly to ``function``.
kwargs: Keyword arguments, passed directly to ``function``.
Return:
callable: A callable that will evaluate a call to ``function`` with
the specified arguments.
'''
NOT_EVALUATED = object()
retval = [NOT_EVALUATED]
def evaluate():
if retval[0] is NOT_EVALUATED:
retval[0] = function(*args, **kwargs)
return retval[0]
return evaluate
|
python
|
{
"resource": ""
}
|
q275927
|
get_object_from_name
|
test
|
def get_object_from_name(name):
''' Returns the named object.
Arguments:
name (str): A string of form `package.subpackage.etc.module.property`.
This function will import `package.subpackage.etc.module` and
return `property` from that module.
'''
dot = name.rindex(".")
mod_name, property_name = name[:dot], name[dot + 1:]
__import__(mod_name)
return getattr(sys.modules[mod_name], property_name)
|
python
|
{
"resource": ""
}
|
q275928
|
InvoiceController.for_cart
|
test
|
def for_cart(cls, cart):
''' Returns an invoice object for a given cart at its current revision.
If such an invoice does not exist, the cart is validated, and if valid,
an invoice is generated.'''
cart.refresh_from_db()
try:
invoice = commerce.Invoice.objects.exclude(
status=commerce.Invoice.STATUS_VOID,
).get(
cart=cart,
cart_revision=cart.revision,
)
except ObjectDoesNotExist:
cart_controller = CartController(cart)
cart_controller.validate_cart() # Raises ValidationError on fail.
cls.update_old_invoices(cart)
invoice = cls._generate_from_cart(cart)
return cls(invoice)
|
python
|
{
"resource": ""
}
|
q275929
|
InvoiceController.manual_invoice
|
test
|
def manual_invoice(cls, user, due_delta, description_price_pairs):
''' Generates an invoice for arbitrary items, not held in a user's
cart.
Arguments:
user (User): The user the invoice is being generated for.
due_delta (datetime.timedelta): The length until the invoice is
due.
description_price_pairs ([(str, long or Decimal), ...]): A list of
pairs. Each pair consists of the description for each line item
and the price for that line item. The price will be cast to
Decimal.
Returns:
an Invoice.
'''
line_items = []
for description, price in description_price_pairs:
line_item = commerce.LineItem(
description=description,
quantity=1,
price=Decimal(price),
product=None,
)
line_items.append(line_item)
min_due_time = timezone.now() + due_delta
return cls._generate(user, None, min_due_time, line_items)
|
python
|
{
"resource": ""
}
|
q275930
|
InvoiceController._generate_from_cart
|
test
|
def _generate_from_cart(cls, cart):
''' Generates an invoice for the given cart. '''
cart.refresh_from_db()
# Generate the line items from the cart.
product_items = commerce.ProductItem.objects.filter(cart=cart)
product_items = product_items.select_related(
"product",
"product__category",
)
product_items = product_items.order_by(
"product__category__order", "product__order"
)
if len(product_items) == 0:
raise ValidationError("Your cart is empty.")
discount_items = commerce.DiscountItem.objects.filter(cart=cart)
discount_items = discount_items.select_related(
"discount",
"product",
"product__category",
)
def format_product(product):
return "%s - %s" % (product.category.name, product.name)
def format_discount(discount, product):
description = discount.description
return "%s (%s)" % (description, format_product(product))
line_items = []
for item in product_items:
product = item.product
line_item = commerce.LineItem(
description=format_product(product),
quantity=item.quantity,
price=product.price,
product=product,
)
line_items.append(line_item)
for item in discount_items:
line_item = commerce.LineItem(
description=format_discount(item.discount, item.product),
quantity=item.quantity,
price=cls.resolve_discount_value(item) * -1,
product=item.product,
)
line_items.append(line_item)
# Generate the invoice
min_due_time = cart.reservation_duration + cart.time_last_updated
return cls._generate(cart.user, cart, min_due_time, line_items)
|
python
|
{
"resource": ""
}
|
q275931
|
InvoiceController._apply_credit_notes
|
test
|
def _apply_credit_notes(cls, invoice):
''' Applies the user's credit notes to the given invoice on creation.
'''
# We only automatically apply credit notes if this is the *only*
# unpaid invoice for this user.
invoices = commerce.Invoice.objects.filter(
user=invoice.user,
status=commerce.Invoice.STATUS_UNPAID,
)
if invoices.count() > 1:
return
notes = commerce.CreditNote.unclaimed().filter(
invoice__user=invoice.user
)
for note in notes:
try:
CreditNoteController(note).apply_to_invoice(invoice)
except ValidationError:
# ValidationError will get raised once we're overpaying.
break
invoice.refresh_from_db()
|
python
|
{
"resource": ""
}
|
q275932
|
InvoiceController.can_view
|
test
|
def can_view(self, user=None, access_code=None):
''' Returns true if the accessing user is allowed to view this invoice,
or if the given access code matches this invoice's user's access code.
'''
if user == self.invoice.user:
return True
if user.is_staff:
return True
if self.invoice.user.attendee.access_code == access_code:
return True
return False
|
python
|
{
"resource": ""
}
|
q275933
|
InvoiceController._refresh
|
test
|
def _refresh(self):
''' Refreshes the underlying invoice and cart objects. '''
self.invoice.refresh_from_db()
if self.invoice.cart:
self.invoice.cart.refresh_from_db()
|
python
|
{
"resource": ""
}
|
q275934
|
InvoiceController.validate_allowed_to_pay
|
test
|
def validate_allowed_to_pay(self):
''' Passes cleanly if we're allowed to pay, otherwise raise
a ValidationError. '''
self._refresh()
if not self.invoice.is_unpaid:
raise ValidationError("You can only pay for unpaid invoices.")
if not self.invoice.cart:
return
if not self._invoice_matches_cart():
raise ValidationError("The registration has been amended since "
"generating this invoice.")
CartController(self.invoice.cart).validate_cart()
|
python
|
{
"resource": ""
}
|
q275935
|
InvoiceController.update_status
|
test
|
def update_status(self):
''' Updates the status of this invoice based upon the total
payments.'''
old_status = self.invoice.status
total_paid = self.invoice.total_payments()
num_payments = commerce.PaymentBase.objects.filter(
invoice=self.invoice,
).count()
remainder = self.invoice.value - total_paid
if old_status == commerce.Invoice.STATUS_UNPAID:
# Invoice had an amount owing
if remainder <= 0:
# Invoice no longer has amount owing
self._mark_paid()
elif total_paid == 0 and num_payments > 0:
# Invoice has multiple payments totalling zero
self._mark_void()
elif old_status == commerce.Invoice.STATUS_PAID:
if remainder > 0:
# Invoice went from having a remainder of zero or less
# to having a positive remainder -- must be a refund
self._mark_refunded()
elif old_status == commerce.Invoice.STATUS_REFUNDED:
# Should not ever change from here
pass
elif old_status == commerce.Invoice.STATUS_VOID:
# Should not ever change from here
pass
# Generate credit notes from residual payments
residual = 0
if self.invoice.is_paid:
if remainder < 0:
residual = 0 - remainder
elif self.invoice.is_void or self.invoice.is_refunded:
residual = total_paid
if residual != 0:
CreditNoteController.generate_from_invoice(self.invoice, residual)
self.email_on_invoice_change(
self.invoice,
old_status,
self.invoice.status,
)
|
python
|
{
"resource": ""
}
|
q275936
|
InvoiceController._mark_paid
|
test
|
def _mark_paid(self):
''' Marks the invoice as paid, and updates the attached cart if
necessary. '''
cart = self.invoice.cart
if cart:
cart.status = commerce.Cart.STATUS_PAID
cart.save()
self.invoice.status = commerce.Invoice.STATUS_PAID
self.invoice.save()
|
python
|
{
"resource": ""
}
|
q275937
|
InvoiceController._invoice_matches_cart
|
test
|
def _invoice_matches_cart(self):
''' Returns true if there is no cart, or if the revision of this
invoice matches the current revision of the cart. '''
self._refresh()
cart = self.invoice.cart
if not cart:
return True
return cart.revision == self.invoice.cart_revision
|
python
|
{
"resource": ""
}
|
q275938
|
InvoiceController.update_validity
|
test
|
def update_validity(self):
''' Voids this invoice if the attached cart is no longer valid because
the cart revision has changed, or the reservations have expired. '''
is_valid = self._invoice_matches_cart()
cart = self.invoice.cart
if self.invoice.is_unpaid and is_valid and cart:
try:
CartController(cart).validate_cart()
except ValidationError:
is_valid = False
if not is_valid:
if self.invoice.total_payments() > 0:
# Free up the payments made to this invoice
self.refund()
else:
self.void()
|
python
|
{
"resource": ""
}
|
q275939
|
InvoiceController.void
|
test
|
def void(self):
''' Voids the invoice if it is valid to do so. '''
if self.invoice.total_payments() > 0:
raise ValidationError("Invoices with payments must be refunded.")
elif self.invoice.is_refunded:
raise ValidationError("Refunded invoices may not be voided.")
if self.invoice.is_paid:
self._release_cart()
self._mark_void()
|
python
|
{
"resource": ""
}
|
q275940
|
InvoiceController.refund
|
test
|
def refund(self):
''' Refunds the invoice by generating a CreditNote for the value of
all of the payments against the cart.
The invoice is marked as refunded, and the underlying cart is marked
as released.
'''
if self.invoice.is_void:
raise ValidationError("Void invoices cannot be refunded")
# Raises a credit note fot the value of the invoice.
amount = self.invoice.total_payments()
if amount == 0:
self.void()
return
CreditNoteController.generate_from_invoice(self.invoice, amount)
self.update_status()
|
python
|
{
"resource": ""
}
|
q275941
|
InvoiceController.email
|
test
|
def email(cls, invoice, kind):
''' Sends out an e-mail notifying the user about something to do
with that invoice. '''
context = {
"invoice": invoice,
}
send_email([invoice.user.email], kind, context=context)
|
python
|
{
"resource": ""
}
|
q275942
|
GenData.update
|
test
|
def update(self, data):
"""Update the object with new data."""
fields = [
'id',
'status',
'type',
'persistence',
'date_start',
'date_finish',
'date_created',
'date_modified',
'checksum',
'processor_name',
'input',
'input_schema',
'output',
'output_schema',
'static',
'static_schema',
'var',
'var_template',
]
self.annotation = {}
for f in fields:
setattr(self, f, data[f])
self.name = data['static']['name'] if 'name' in data['static'] else ''
self.annotation.update(self._flatten_field(data['input'], data['input_schema'], 'input'))
self.annotation.update(self._flatten_field(data['output'], data['output_schema'], 'output'))
self.annotation.update(self._flatten_field(data['static'], data['static_schema'], 'static'))
self.annotation.update(self._flatten_field(data['var'], data['var_template'], 'var'))
|
python
|
{
"resource": ""
}
|
q275943
|
GenData._flatten_field
|
test
|
def _flatten_field(self, field, schema, path):
"""Reduce dicts of dicts to dot separated keys."""
flat = {}
for field_schema, fields, path in iterate_schema(field, schema, path):
name = field_schema['name']
typ = field_schema['type']
label = field_schema['label']
value = fields[name] if name in fields else None
flat[path] = {'name': name, 'value': value, 'type': typ, 'label': label}
return flat
|
python
|
{
"resource": ""
}
|
q275944
|
GenData.print_downloads
|
test
|
def print_downloads(self):
"""Print file fields to standard output."""
for path, ann in self.annotation.items():
if path.startswith('output') and ann['type'] == 'basic:file:':
print("{}: {}".format(path, ann['value']['file']))
|
python
|
{
"resource": ""
}
|
q275945
|
GenData.download
|
test
|
def download(self, field):
"""Download a file.
:param field: file field to download
:type field: string
:rtype: a file handle
"""
if not field.startswith('output'):
raise ValueError("Only processor results (output.* fields) can be downloaded")
if field not in self.annotation:
raise ValueError("Download field {} does not exist".format(field))
ann = self.annotation[field]
if ann['type'] != 'basic:file:':
raise ValueError("Only basic:file: field can be downloaded")
return next(self.gencloud.download([self.id], field))
|
python
|
{
"resource": ""
}
|
q275946
|
Genesis.project_data
|
test
|
def project_data(self, project):
"""Return a list of Data objects for given project.
:param project: ObjectId or slug of Genesis project
:type project: string
:rtype: list of Data objects
"""
projobjects = self.cache['project_objects']
objects = self.cache['objects']
project_id = str(project)
if not re.match('^[0-9a-fA-F]{24}$', project_id):
# project_id is a slug
projects = self.api.case.get(url_slug=project_id)['objects']
if len(projects) != 1:
raise ValueError(msg='Attribute project not a slug or ObjectId: {}'.format(project_id))
project_id = str(projects[0]['id'])
if project_id not in projobjects:
projobjects[project_id] = []
data = self.api.data.get(case_ids__contains=project_id)['objects']
for d in data:
_id = d['id']
if _id in objects:
# Update existing object
objects[_id].update(d)
else:
# Insert new object
objects[_id] = GenData(d, self)
projobjects[project_id].append(objects[_id])
# Hydrate reference fields
for d in projobjects[project_id]:
while True:
ref_annotation = {}
remove_annotation = []
for path, ann in d.annotation.items():
if ann['type'].startswith('data:'):
# Referenced data object found
# Copy annotation
if ann['value'] in self.cache['objects']:
annotation = self.cache['objects'][ann['value']].annotation
ref_annotation.update({path + '.' + k: v for k, v in annotation.items()})
remove_annotation.append(path)
if ref_annotation:
d.annotation.update(ref_annotation)
for path in remove_annotation:
del d.annotation[path]
else:
break
return projobjects[project_id]
|
python
|
{
"resource": ""
}
|
q275947
|
Genesis.processors
|
test
|
def processors(self, processor_name=None):
"""Return a list of Processor objects.
:param project_id: ObjectId of Genesis project
:type project_id: string
:rtype: list of Processor objects
"""
if processor_name:
return self.api.processor.get(name=processor_name)['objects']
else:
return self.api.processor.get()['objects']
|
python
|
{
"resource": ""
}
|
q275948
|
Genesis.print_processor_inputs
|
test
|
def print_processor_inputs(self, processor_name):
"""Print processor input fields and types.
:param processor_name: Processor object name
:type processor_name: string
"""
p = self.processors(processor_name=processor_name)
if len(p) == 1:
p = p[0]
else:
Exception('Invalid processor name')
for field_schema, _, _ in iterate_schema({}, p['input_schema'], 'input'):
name = field_schema['name']
typ = field_schema['type']
# value = fields[name] if name in fields else None
print("{} -> {}".format(name, typ))
|
python
|
{
"resource": ""
}
|
q275949
|
Genesis.rundata
|
test
|
def rundata(self, strjson):
"""POST JSON data object to server"""
d = json.loads(strjson)
return self.api.data.post(d)
|
python
|
{
"resource": ""
}
|
q275950
|
Genesis.upload
|
test
|
def upload(self, project_id, processor_name, **fields):
"""Upload files and data objects.
:param project_id: ObjectId of Genesis project
:type project_id: string
:param processor_name: Processor object name
:type processor_name: string
:param fields: Processor field-value pairs
:type fields: args
:rtype: HTTP Response object
"""
p = self.processors(processor_name=processor_name)
if len(p) == 1:
p = p[0]
else:
Exception('Invalid processor name {}'.format(processor_name))
for field_name, field_val in fields.items():
if field_name not in p['input_schema']:
Exception("Field {} not in processor {} inputs".format(field_name, p['name']))
if find_field(p['input_schema'], field_name)['type'].startswith('basic:file:'):
if not os.path.isfile(field_val):
Exception("File {} not found".format(field_val))
inputs = {}
for field_name, field_val in fields.items():
if find_field(p['input_schema'], field_name)['type'].startswith('basic:file:'):
file_temp = self._upload_file(field_val)
if not file_temp:
Exception("Upload failed for {}".format(field_val))
inputs[field_name] = {
'file': field_val,
'file_temp': file_temp
}
else:
inputs[field_name] = field_val
d = {
'status': 'uploading',
'case_ids': [project_id],
'processor_name': processor_name,
'input': inputs,
}
return self.create(d)
|
python
|
{
"resource": ""
}
|
q275951
|
Genesis._upload_file
|
test
|
def _upload_file(self, fn):
"""Upload a single file on the platform.
File is uploaded in chunks of 1,024 bytes.
:param fn: File path
:type fn: string
"""
size = os.path.getsize(fn)
counter = 0
base_name = os.path.basename(fn)
session_id = str(uuid.uuid4())
with open(fn, 'rb') as f:
while True:
response = None
chunk = f.read(CHUNK_SIZE)
if not chunk:
break
for i in range(5):
content_range = 'bytes {}-{}/{}'.format(counter * CHUNK_SIZE,
counter * CHUNK_SIZE + len(chunk) - 1, size)
if i > 0 and response is not None:
print("Chunk upload failed (error {}): repeating {}"
.format(response.status_code, content_range))
response = requests.post(urlparse.urljoin(self.url, 'upload/'),
auth=self.auth,
data=chunk,
headers={
'Content-Disposition': 'attachment; filename="{}"'.format(base_name),
'Content-Length': size,
'Content-Range': content_range,
'Content-Type': 'application/octet-stream',
'Session-Id': session_id})
if response.status_code in [200, 201]:
break
else:
# Upload of a chunk failed (5 retries)
return None
progress = 100. * (counter * CHUNK_SIZE + len(chunk)) / size
sys.stdout.write("\r{:.0f} % Uploading {}".format(progress, fn))
sys.stdout.flush()
counter += 1
print()
return session_id
|
python
|
{
"resource": ""
}
|
q275952
|
Genesis.download
|
test
|
def download(self, data_objects, field):
"""Download files of data objects.
:param data_objects: Data object ids
:type data_objects: list of UUID strings
:param field: Download field name
:type field: string
:rtype: generator of requests.Response objects
"""
if not field.startswith('output'):
raise ValueError("Only processor results (output.* fields) can be downloaded")
for o in data_objects:
o = str(o)
if re.match('^[0-9a-fA-F]{24}$', o) is None:
raise ValueError("Invalid object id {}".format(o))
if o not in self.cache['objects']:
self.cache['objects'][o] = GenData(self.api.data(o).get(), self)
if field not in self.cache['objects'][o].annotation:
raise ValueError("Download field {} does not exist".format(field))
ann = self.cache['objects'][o].annotation[field]
if ann['type'] != 'basic:file:':
raise ValueError("Only basic:file: field can be downloaded")
for o in data_objects:
ann = self.cache['objects'][o].annotation[field]
url = urlparse.urljoin(self.url, 'data/{}/{}'.format(o, ann['value']['file']))
yield requests.get(url, stream=True, auth=self.auth)
|
python
|
{
"resource": ""
}
|
q275953
|
get_subclasses
|
test
|
def get_subclasses(c):
"""Gets the subclasses of a class."""
subclasses = c.__subclasses__()
for d in list(subclasses):
subclasses.extend(get_subclasses(d))
return subclasses
|
python
|
{
"resource": ""
}
|
q275954
|
Action.get_repo_and_project
|
test
|
def get_repo_and_project(self):
"""Returns repository and project."""
app = self.app
# Get repo
repo = app.data.apply('github-repo', app.args.github_repo,
app.prompt_repo,
on_load=app.github.get_repo,
on_save=lambda r: r.id
)
assert repo, "repository not found."
# Get project
project = app.data.apply('asana-project', app.args.asana_project,
app.prompt_project,
on_load=app.asana.projects.find_by_id,
on_save=lambda p: p['id']
)
assert project, "project not found."
# Set first issue
first_issue = app.data.apply('first-issue', app.args.first_issue,
"set the first issue to sync with [1 for new repos]",
on_save=int)
assert first_issue
assert first_issue >= 0, "issue must be positive"
app.sync_data()
return repo, project
|
python
|
{
"resource": ""
}
|
q275955
|
get_variant_phenotypes_with_suggested_changes
|
test
|
def get_variant_phenotypes_with_suggested_changes(variant_id_list):
'''for each variant, yields evidence and associated phenotypes, both current and suggested'''
variants = civic.get_variants_by_ids(variant_id_list)
evidence = list()
for variant in variants:
evidence.extend(variant.evidence)
for e in evidence:
suggested_changes_url = f'https://civicdb.org/api/evidence_items/{e.id}/suggested_changes'
resp = requests.get(suggested_changes_url)
resp.raise_for_status()
suggested_changes = dict()
for suggested_change in resp.json():
pheno_changes = suggested_change['suggested_changes'].get('phenotype_ids', None)
if pheno_changes is None:
continue
a, b = pheno_changes
added = set(b) - set(a)
deleted = set(a) - set(b)
rid = suggested_change['id']
suggested_changes[rid] = {'added': added, 'deleted': deleted}
yield e, {'suggested_changes': suggested_changes, 'current': set([x.id for x in e.phenotypes])}
|
python
|
{
"resource": ""
}
|
q275956
|
get_variant_phenotypes_with_suggested_changes_merged
|
test
|
def get_variant_phenotypes_with_suggested_changes_merged(variant_id_list):
'''for each variant, yields evidence and merged phenotype from applying suggested changes to current'''
for evidence, phenotype_status in get_variant_phenotypes_with_suggested_changes(variant_id_list):
final = phenotype_status['current']
for rid in sorted(phenotype_status['suggested_changes']):
changes = phenotype_status['suggested_changes'][rid]
final = final - changes['deleted']
final = final | changes['added']
if final:
yield evidence, final
|
python
|
{
"resource": ""
}
|
q275957
|
search_variants_by_coordinates
|
test
|
def search_variants_by_coordinates(coordinate_query, search_mode='any'):
"""
Search the cache for variants matching provided coordinates using the corresponding search mode.
:param coordinate_query: A civic CoordinateQuery object
start: the genomic start coordinate of the query
stop: the genomic end coordinate of the query
chr: the GRCh37 chromosome of the query (e.g. "7", "X")
alt: the alternate allele at the coordinate [optional]
:param search_mode: ['any', 'include_smaller', 'include_larger', 'exact']
any: any overlap between a query and a variant is a match
include_smaller: variants must fit within the coordinates of the query
include_larger: variants must encompass the coordinates of the query
exact: variants must match coordinates precisely, as well as alternate
allele, if provided
search_mode is 'exact' by default
:return: Returns a list of variant hashes matching the coordinates and search_mode
"""
get_all_variants()
ct = COORDINATE_TABLE
start_idx = COORDINATE_TABLE_START
stop_idx = COORDINATE_TABLE_STOP
chr_idx = COORDINATE_TABLE_CHR
start = int(coordinate_query.start)
stop = int(coordinate_query.stop)
chromosome = str(coordinate_query.chr)
# overlapping = (start <= ct.stop) & (stop >= ct.start)
left_idx = chr_idx.searchsorted(chromosome)
right_idx = chr_idx.searchsorted(chromosome, side='right')
chr_ct_idx = chr_idx[left_idx:right_idx].index
right_idx = start_idx.searchsorted(stop, side='right')
start_ct_idx = start_idx[:right_idx].index
left_idx = stop_idx.searchsorted(start)
stop_ct_idx = stop_idx[left_idx:].index
match_idx = chr_ct_idx & start_ct_idx & stop_ct_idx
m_df = ct.loc[match_idx, ]
if search_mode == 'any':
var_digests = m_df.v_hash.to_list()
return [CACHE[v] for v in var_digests]
elif search_mode == 'include_smaller':
match_idx = (start <= m_df.start) & (stop >= m_df.stop)
elif search_mode == 'include_larger':
match_idx = (start >= m_df.start) & (stop <= m_df.stop)
elif search_mode == 'exact':
match_idx = (start == m_df.stop) & (stop == m_df.start)
if coordinate_query.alt:
match_idx = match_idx & (coordinate_query.alt == m_df.alt)
else:
raise ValueError("unexpected search mode")
var_digests = m_df.loc[match_idx,].v_hash.to_list()
return [CACHE[v] for v in var_digests]
|
python
|
{
"resource": ""
}
|
q275958
|
bulk_search_variants_by_coordinates
|
test
|
def bulk_search_variants_by_coordinates(sorted_queries, search_mode='any'):
"""
An interator to search the cache for variants matching the set of sorted coordinates and yield
matches corresponding to the search mode.
:param sorted_queries: A list of civic CoordinateQuery objects, sorted by coordinate.
start: the genomic start coordinate of the query
stop: the genomic end coordinate of the query
chr: the GRCh37 chromosome of the query (e.g. "7", "X")
alt: the alternate allele at the coordinate [optional]
:param search_mode: ['any', 'include_smaller', 'include_larger', 'exact']
any: any overlap between a query and a variant is a match
include_smaller: variants must fit within the coordinates of the query
include_larger: variants must encompass the coordinates of the query
exact: variants must match coordinates precisely, as well as alternate
allele, if provided
search_mode is 'exact' by default
:yield: Yields (query, match) tuples for each identified match
"""
def is_sorted(prev_q, current_q):
if prev_q['chr'] < current_q['chr']:
return True
if prev_q['chr'] > current_q['chr']:
return False
if prev_q['start'] < current_q['start']:
return True
if prev_q['start'] > current_q['start']:
return False
if prev_q['stop'] < current_q['stop']:
return True
if prev_q['stop'] > current_q['stop']:
return False
return True
ct_pointer = 0
query_pointer = 0
last_query_pointer = -1
match_start = None
ct = MODULE.COORDINATE_TABLE
matches = defaultdict(list)
Match = namedtuple('Match', ct.columns)
while query_pointer < len(sorted_queries) and ct_pointer < len(ct):
if last_query_pointer != query_pointer:
q = sorted_queries[query_pointer]
if match_start is not None:
ct_pointer = match_start
match_start = None
last_query_pointer = query_pointer
c = ct.iloc[ct_pointer]
q_chr = str(q.chr)
c_chr = c.chr
if q_chr < c_chr:
query_pointer += 1
continue
if q_chr > c_chr:
ct_pointer += 1
continue
q_start = int(q.start)
c_start = c.start
q_stop = int(q.stop)
c_stop = c.stop
if q_start > c_stop:
ct_pointer += 1
continue
if q_stop < c_start:
query_pointer += 1
continue
if search_mode == 'any':
matches[q].append(c.to_dict())
elif search_mode == 'exact' and q_start == c_start and q_stop == c_stop:
q_alt = q.alt
c_alt = c.alt
if not (q_alt and c_alt and q_alt != c_alt):
matches[q].append(Match(**c.to_dict()))
elif search_mode == 'include_smaller':
raise NotImplementedError
elif search_mode == 'include_larger':
raise NotImplementedError
if match_start is None:
match_start = ct_pointer
ct_pointer += 1
return dict(matches)
|
python
|
{
"resource": ""
}
|
q275959
|
CivicRecord.update
|
test
|
def update(self, allow_partial=True, force=False, **kwargs):
"""Updates record and returns True if record is complete after update, else False."""
if kwargs:
self.__init__(partial=allow_partial, force=force, **kwargs)
return not self._partial
if not force and CACHE.get(hash(self)):
cached = CACHE[hash(self)]
for field in self._SIMPLE_FIELDS | self._COMPLEX_FIELDS:
v = getattr(cached, field)
setattr(self, field, v)
self._partial = False
logging.info(f'Loading {str(self)} from cache')
return True
resp_dict = element_lookup_by_id(self.type, self.id)
self.__init__(partial=False, **resp_dict)
return True
|
python
|
{
"resource": ""
}
|
q275960
|
ToolApp.uniqify
|
test
|
def uniqify(cls, seq):
"""Returns a unique list of seq"""
seen = set()
seen_add = seen.add
return [ x for x in seq if x not in seen and not seen_add(x)]
|
python
|
{
"resource": ""
}
|
q275961
|
ToolApp.authenticate
|
test
|
def authenticate(self):
"""Connects to Github and Asana and authenticates via OAuth."""
if self.oauth:
return False
# Save asana.
self.settings.apply('api-asana', self.args.asana_api,
"enter asana api key")
# Save github.com
self.settings.apply('api-github', self.args.github_api,
"enter github.com token")
logging.debug("authenticating asana api.")
self.asana = Client.basic_auth(self.settings['api-asana'])
self.asana_errors = asana_errors
self.asana_me = self.asana.users.me()
logging.debug("authenticating github api")
self.github = Github(self.settings['api-github'])
self.github_user = self.github.get_user()
self.oauth = True
|
python
|
{
"resource": ""
}
|
q275962
|
ToolApp._list_select
|
test
|
def _list_select(cls, lst, prompt, offset=0):
"""Given a list of values and names, accepts the index value or name."""
inp = raw_input("select %s: " % prompt)
assert inp, "value required."
try:
return lst[int(inp)+offset]
except ValueError:
return inp
except IndexError:
assert False, "bad value."
|
python
|
{
"resource": ""
}
|
q275963
|
ToolApp.get_saved_issue_data
|
test
|
def get_saved_issue_data(self, issue, namespace='open'):
"""Returns issue data from local data.
Args:
issue:
`int`. Github issue number.
namespace:
`str`. Namespace for storing this issue.
"""
if isinstance(issue, int):
issue_number = str(issue)
elif isinstance(issue, basestring):
issue_number = issue
else:
issue_number = issue.number
issue_data_key = self._issue_data_key(namespace)
issue_data = self.data.get(issue_data_key,
{})
_data = issue_data.get(str(issue_number), {})
issue_data[str(issue_number)] = _data
return _data
|
python
|
{
"resource": ""
}
|
q275964
|
ToolApp.move_saved_issue_data
|
test
|
def move_saved_issue_data(self, issue, ns, other_ns):
"""Moves an issue_data from one namespace to another."""
if isinstance(issue, int):
issue_number = str(issue)
elif isinstance(issue, basestring):
issue_number = issue
else:
issue_number = issue.number
issue_data_key = self._issue_data_key(ns)
other_issue_data_key = self._issue_data_key(other_ns)
issue_data = self.data.get(issue_data_key,
{})
other_issue_data = self.data.get(other_issue_data_key,
{})
_id = issue_data.pop(issue_number, None)
if _id:
other_issue_data[issue_number] = _id
self.data[other_issue_data_key] = other_issue_data
self.data[issue_data_key] = issue_data
|
python
|
{
"resource": ""
}
|
q275965
|
ToolApp.get_saved_task_data
|
test
|
def get_saved_task_data(self, task):
"""Returns task data from local data.
Args:
task:
`int`. Asana task number.
"""
if isinstance(task, int):
task_number = str(task)
elif isinstance(task, basestring):
task_number = task
else:
task_number = task['id']
task_data_key = self._task_data_key()
task_data = self.data.get(task_data_key, {})
_data = task_data.get(str(task_number), {})
task_data[str(task_number)] = _data
return _data
|
python
|
{
"resource": ""
}
|
q275966
|
ToolApp.get_asana_task
|
test
|
def get_asana_task(self, asana_task_id):
"""Retrieves a task from asana."""
try:
return self.asana.tasks.find_by_id(asana_task_id)
except asana_errors.NotFoundError:
return None
except asana_errors.ForbiddenError:
return None
|
python
|
{
"resource": ""
}
|
q275967
|
JSONData.save
|
test
|
def save(self):
"""Save data."""
with open(self.filename, 'wb') as file:
self.prune()
self.data['version'] = self.version
json.dump(self.data,
file,
sort_keys=True, indent=2)
|
python
|
{
"resource": ""
}
|
q275968
|
JSONData.apply
|
test
|
def apply(self, key, value, prompt=None,
on_load=lambda a: a, on_save=lambda a: a):
"""Applies a setting value to a key, if the value is not `None`.
Returns without prompting if either of the following:
* `value` is not `None`
* already present in the dictionary
Args:
prompt:
May either be a string to prompt via `raw_input` or a
method (callable) that returns the value.
on_load:
lambda. Value is passed through here after loaded.
on_save:
lambda. Value is saved as this value.
"""
# Reset value if flag exists without value
if value == '':
value = None
if key and self.data.has_key(key): del self.data[key]
# If value is explicitly set from args.
if value is not None:
value = on_load(value)
if key: self.data[key] = on_save(value)
return value
elif not key or not self.has_key(key):
if callable(prompt):
value = prompt()
elif prompt is not None:
value = raw_input(prompt + ": ")
if value is None:
if self.data.has_key(key): del self.data[key]
return None
self.data[key] = on_save(value)
return value
return on_load(self.data[key])
|
python
|
{
"resource": ""
}
|
q275969
|
transport_task
|
test
|
def transport_task(func):
"""Decorator for retrying tasks with special cases."""
def wrapped_func(*args, **kwargs):
tries = 0
while True:
try:
try:
return func(*args, **kwargs)
except (asana_errors.InvalidRequestError,
asana_errors.NotFoundError), exc:
logging.warn("warning: invalid request: %r", exc)
except asana_errors.ForbiddenError, exc:
logging.warn("forbidden error: %r", exc)
except asana_errors.NotFoundError, exc:
logging.warn("not found error: %r", exc)
return None
except asana_errors.RetryableAsanaError, retry_exc:
tries += 1
logging.warn("retry exception %r on try %d", retry_exc, tries)
if tries >= 3:
raise
except Exception, exc:
logging.exception("Exception in transport.")
return
return wrapped_func
|
python
|
{
"resource": ""
}
|
q275970
|
flush
|
test
|
def flush(callback=None):
"""Waits until queue is empty."""
while True:
if shutdown_event.is_set():
return
if callable(callback):
callback()
try:
item = queue.get(timeout=1)
queue.put(item) # put it back, we're just peeking.
except Queue.Empty:
return
|
python
|
{
"resource": ""
}
|
q275971
|
task_create
|
test
|
def task_create(asana_workspace_id, name, notes, assignee, projects,
completed, **kwargs):
"""Creates a task"""
put("task_create",
asana_workspace_id=asana_workspace_id,
name=name,
notes=notes,
assignee=assignee,
projects=projects,
completed=completed,
**kwargs)
|
python
|
{
"resource": ""
}
|
q275972
|
format_task_numbers_with_links
|
test
|
def format_task_numbers_with_links(tasks):
"""Returns formatting for the tasks section of asana."""
project_id = data.get('asana-project', None)
def _task_format(task_id):
if project_id:
asana_url = tool.ToolApp.make_asana_url(project_id, task_id)
return "[#%d](%s)" % (task_id, asana_url)
else:
return "#%d" % task_id
return "\n".join([_task_format(tid) for tid in tasks])
|
python
|
{
"resource": ""
}
|
q275973
|
TransportWorker.create_missing_task
|
test
|
def create_missing_task(self,
asana_workspace_id,
name,
assignee,
projects,
completed,
issue_number,
issue_html_url,
issue_state,
issue_body,
tasks,
labels,
label_tag_map):
"""Creates a missing task."""
task = self.asana.tasks.create_in_workspace(
asana_workspace_id,
{
'name': name,
'notes': issue_body,
'assignee': assignee,
'projects': projects,
'completed': completed,
})
# Announce task git issue
task_id = task['id']
put("create_story",
task_id=task_id,
text="Git Issue #%d: \n"
"%s" % (
issue_number,
issue_html_url,
)
)
put("apply_tasks_to_issue",
tasks=[task_id],
issue_number=issue_number,
issue_body=issue_body,
)
# Save task to drive
put_setting("save_issue_data_task",
issue=issue_number,
task_id=task_id,
namespace=issue_state)
tasks.append(task_id)
# Sync tags/labels
put("sync_tags",
tasks=tasks,
labels=labels,
label_tag_map=label_tag_map)
|
python
|
{
"resource": ""
}
|
q275974
|
GenProject.data_types
|
test
|
def data_types(self):
"""Return a list of data types."""
data = self.gencloud.project_data(self.id)
return sorted(set(d.type for d in data))
|
python
|
{
"resource": ""
}
|
q275975
|
ekm_log
|
test
|
def ekm_log(logstr, priority=3):
""" Send string to module level log
Args:
logstr (str): string to print.
priority (int): priority, supports 3 (default) and 4 (special).
"""
if priority <= ekmmeters_log_level:
dt = datetime.datetime
stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M.%f")
ekmmeters_log_func("[EKM Meter Debug Message: " + stamp + "] -> " + logstr)
pass
|
python
|
{
"resource": ""
}
|
q275976
|
SerialPort.initPort
|
test
|
def initPort(self):
""" Required initialization call, wraps pyserial constructor. """
try:
self.m_ser = serial.Serial(port=self.m_ttyport,
baudrate=self.m_baudrate,
timeout=0,
parity=serial.PARITY_EVEN,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.SEVENBITS,
rtscts=False)
ekm_log("Pyserial version = " + serial.VERSION)
ekm_log("Port = " + self.m_ttyport)
ekm_log("Rate = " + str(self.m_baudrate))
time.sleep(self.m_init_wait)
return True
except:
ekm_log(traceback.format_exc(sys.exc_info()))
return False
|
python
|
{
"resource": ""
}
|
q275977
|
SerialPort.setPollingValues
|
test
|
def setPollingValues(self, max_waits, wait_sleep):
""" Optional polling loop control
Args:
max_waits (int): waits
wait_sleep (int): ms per wait
"""
self.m_max_waits = max_waits
self.m_wait_sleep = wait_sleep
|
python
|
{
"resource": ""
}
|
q275978
|
MeterDB.combineAB
|
test
|
def combineAB(self):
""" Use the serial block definitions in V3 and V4 to create one field list. """
v4definition_meter = V4Meter()
v4definition_meter.makeAB()
defv4 = v4definition_meter.getReadBuffer()
v3definition_meter = V3Meter()
v3definition_meter.makeReturnFormat()
defv3 = v3definition_meter.getReadBuffer()
for fld in defv3:
if fld not in self.m_all_fields:
compare_fld = fld.upper()
if not "RESERVED" in compare_fld and not "CRC" in compare_fld:
self.m_all_fields[fld] = defv3[fld]
for fld in defv4:
if fld not in self.m_all_fields:
compare_fld = fld.upper()
if not "RESERVED" in compare_fld and not "CRC" in compare_fld:
self.m_all_fields[fld] = defv4[fld]
pass
|
python
|
{
"resource": ""
}
|
q275979
|
SqliteMeterDB.renderJsonReadsSince
|
test
|
def renderJsonReadsSince(self, timestamp, meter):
""" Simple since Time_Stamp query returned as JSON records.
Args:
timestamp (int): Epoch time in seconds.
meter (str): 12 character meter address to query
Returns:
str: JSON rendered read records.
"""
result = ""
try:
connection = sqlite3.connect(self.m_connection_string)
connection.row_factory = self.dict_factory
select_cursor = connection.cursor()
select_cursor.execute("select * from Meter_Reads where " + Field.Time_Stamp +
" > " + str(timestamp) + " and " + Field.Meter_Address +
"= '" + meter + "';")
reads = select_cursor.fetchall()
result = json.dumps(reads, indent=4)
except:
ekm_log(traceback.format_exc(sys.exc_info()))
return result
|
python
|
{
"resource": ""
}
|
q275980
|
Meter.setContext
|
test
|
def setContext(self, context_str):
""" Set context string for serial command. Private setter.
Args:
context_str (str): Command specific string.
"""
if (len(self.m_context) == 0) and (len(context_str) >= 7):
if context_str[0:7] != "request":
ekm_log("Context: " + context_str)
self.m_context = context_str
|
python
|
{
"resource": ""
}
|
q275981
|
Meter.calcPF
|
test
|
def calcPF(pf):
""" Simple wrap to calc legacy PF value
Args:
pf: meter power factor reading
Returns:
int: legacy push pf
"""
pf_y = pf[:1]
pf_x = pf[1:]
result = 100
if pf_y == CosTheta.CapacitiveLead:
result = 200 - int(pf_x)
elif pf_y == CosTheta.InductiveLag:
result = int(pf_x)
return result
|
python
|
{
"resource": ""
}
|
q275982
|
Meter.setMaxDemandPeriod
|
test
|
def setMaxDemandPeriod(self, period, password="00000000"):
""" Serial call to set max demand period.
Args:
period (int): : as int.
password (str): Optional password.
Returns:
bool: True on completion with ACK.
"""
result = False
self.setContext("setMaxDemandPeriod")
try:
if period < 1 or period > 3:
self.writeCmdMsg("Correct parameter: 1 = 15 minute, 2 = 30 minute, 3 = hour")
self.setContext("")
return result
if not self.request(False):
self.writeCmdMsg("Bad read CRC on setting")
else:
if not self.serialCmdPwdAuth(password):
self.writeCmdMsg("Password failure")
else:
req_str = "015731023030353028" + binascii.hexlify(str(period)).zfill(2) + "2903"
req_str += self.calc_crc16(req_str[2:].decode("hex"))
self.m_serial_port.write(req_str.decode("hex"))
if self.m_serial_port.getResponse(self.getContext()).encode("hex") == "06":
self.writeCmdMsg("Success(setMaxDemandPeriod): 06 returned.")
result = True
self.serialPostEnd()
except:
ekm_log(traceback.format_exc(sys.exc_info()))
self.setContext("")
return result
|
python
|
{
"resource": ""
}
|
q275983
|
Meter.setMeterPassword
|
test
|
def setMeterPassword(self, new_pwd, pwd="00000000"):
""" Serial Call to set meter password. USE WITH CAUTION.
Args:
new_pwd (str): 8 digit numeric password to set
pwd (str): Old 8 digit numeric password.
Returns:
bool: True on completion with ACK.
"""
result = False
self.setContext("setMeterPassword")
try:
if len(new_pwd) != 8 or len(pwd) != 8:
self.writeCmdMsg("Passwords must be exactly eight characters.")
self.setContext("")
return result
if not self.request(False):
self.writeCmdMsg("Pre command read failed: check serial line.")
else:
if not self.serialCmdPwdAuth(pwd):
self.writeCmdMsg("Password failure")
else:
req_pwd = binascii.hexlify(new_pwd.zfill(8))
req_str = "015731023030323028" + req_pwd + "2903"
req_str += self.calc_crc16(req_str[2:].decode("hex"))
self.m_serial_port.write(req_str.decode("hex"))
if self.m_serial_port.getResponse(self.getContext()).encode("hex") == "06":
self.writeCmdMsg("Success(setMeterPassword): 06 returned.")
result = True
self.serialPostEnd()
except:
ekm_log(traceback.format_exc(sys.exc_info()))
self.setContext("")
return result
|
python
|
{
"resource": ""
}
|
q275984
|
Meter.unpackStruct
|
test
|
def unpackStruct(self, data, def_buf):
""" Wrapper for struct.unpack with SerialBlock buffer definitionns.
Args:
data (str): Implicit cast bytes to str, serial port return.
def_buf (SerialBlock): Block object holding field lengths.
Returns:
tuple: parsed result of struct.unpack() with field definitions.
"""
struct_str = "="
for fld in def_buf:
if not def_buf[fld][MeterData.CalculatedFlag]:
struct_str = struct_str + str(def_buf[fld][MeterData.SizeValue]) + "s"
if len(data) == 255:
contents = struct.unpack(struct_str, str(data))
else:
self.writeCmdMsg("Length error. Len() size = " + str(len(data)))
contents = ()
return contents
|
python
|
{
"resource": ""
}
|
q275985
|
Meter.convertData
|
test
|
def convertData(self, contents, def_buf, kwh_scale=ScaleKWH.EmptyScale):
""" Move data from raw tuple into scaled and conveted values.
Args:
contents (tuple): Breakout of passed block from unpackStruct().
def_buf (): Read buffer destination.
kwh_scale (int): :class:`~ekmmeters.ScaleKWH` as int, from Field.kWhScale`
Returns:
bool: True on completion.
"""
log_str = ""
count = 0
# getting scale does not require a full read. It does require that the
# reads have the scale value in the first block read. This requirement
# is filled by default in V3 and V4 requests
if kwh_scale == ScaleKWH.EmptyScale:
scale_offset = int(def_buf.keys().index(Field.kWh_Scale))
self.m_kwh_precision = kwh_scale = int(contents[scale_offset])
for fld in def_buf:
if def_buf[fld][MeterData.CalculatedFlag]:
count += 1
continue
if len(contents) == 0:
count += 1
continue
try: # scrub up messes on a field by field basis
raw_data = contents[count]
fld_type = def_buf[fld][MeterData.TypeValue]
fld_scale = def_buf[fld][MeterData.ScaleValue]
if fld_type == FieldType.Float:
float_data = float(str(raw_data))
divisor = 1
if fld_scale == ScaleType.KWH:
divisor = 1
if kwh_scale == ScaleKWH.Scale10:
divisor = 10
elif kwh_scale == ScaleKWH.Scale100:
divisor = 100
elif (kwh_scale != ScaleKWH.NoScale) and (kwh_scale != ScaleKWH.EmptyScale):
ekm_log("Unrecognized kwh scale.")
elif fld_scale == ScaleType.Div10:
divisor = 10
elif fld_scale == ScaleType.Div100:
divisor = 100
elif fld_scale != ScaleType.No:
ekm_log("Unrecognized float scale.")
float_data /= divisor
float_data_str = str(float_data)
def_buf[fld][MeterData.StringValue] = float_data_str
def_buf[fld][MeterData.NativeValue] = float_data
elif fld_type == FieldType.Hex:
hex_data = raw_data.encode('hex')
def_buf[fld][MeterData.StringValue] = hex_data
def_buf[fld][MeterData.NativeValue] = hex_data
elif fld_type == FieldType.Int:
integer_data = int(raw_data)
integer_data_str = str(integer_data)
if len(integer_data_str) == 0:
integer_data_str = str(0)
def_buf[fld][MeterData.StringValue] = integer_data_str
def_buf[fld][MeterData.NativeValue] = integer_data
elif fld_type == FieldType.String:
string_data = str(raw_data)
def_buf[fld][MeterData.StringValue] = string_data
def_buf[fld][MeterData.NativeValue] = string_data
elif fld_type == FieldType.PowerFactor:
def_buf[fld][MeterData.StringValue] = str(raw_data)
def_buf[fld][MeterData.NativeValue] = str(raw_data)
else:
ekm_log("Unrecognized field type")
log_str = log_str + '"' + fld + '": "' + def_buf[fld][MeterData.StringValue] + '"\n'
except:
ekm_log("Exception on Field:" + str(fld))
ekm_log(traceback.format_exc(sys.exc_info()))
self.writeCmdMsg("Exception on Field:" + str(fld))
count += 1
return True
|
python
|
{
"resource": ""
}
|
q275986
|
Meter.jsonRender
|
test
|
def jsonRender(self, def_buf):
""" Translate the passed serial block into string only JSON.
Args:
def_buf (SerialBlock): Any :class:`~ekmmeters.SerialBlock` object.
Returns:
str: JSON rendering of meter record.
"""
try:
ret_dict = SerialBlock()
ret_dict[Field.Meter_Address] = self.getMeterAddress()
for fld in def_buf:
compare_fld = fld.upper()
if not "RESERVED" in compare_fld and not "CRC" in compare_fld:
ret_dict[str(fld)] = def_buf[fld][MeterData.StringValue]
except:
ekm_log(traceback.format_exc(sys.exc_info()))
return ""
return json.dumps(ret_dict, indent=4)
|
python
|
{
"resource": ""
}
|
q275987
|
Meter.crcMeterRead
|
test
|
def crcMeterRead(self, raw_read, def_buf):
""" Internal read CRC wrapper.
Args:
raw_read (str): Bytes with implicit string cast from serial read
def_buf (SerialBlock): Populated read buffer.
Returns:
bool: True if passed CRC equals calculated CRC.
"""
try:
if len(raw_read) == 0:
ekm_log("(" + self.m_context + ") Empty return read.")
return False
sent_crc = self.calc_crc16(raw_read[1:-2])
logstr = "(" + self.m_context + ")CRC sent = " + str(def_buf["crc16"][MeterData.StringValue])
logstr += " CRC calc = " + sent_crc
ekm_log(logstr)
if int(def_buf["crc16"][MeterData.StringValue], 16) == int(sent_crc, 16):
return True
# A cross simple test lines on a USB serial adapter, these occur every
# 1000 to 2000 reads, and they show up here as a bad unpack or
# a bad crc type call. In either case, we suppress them a log will
# become quite large. ekmcrc errors come through as type errors.
# Failures of int type conversion in 16 bit conversion occur as value
# errors.
except struct.error:
ekm_log(str(sys.exc_info()))
for frame in traceback.extract_tb(sys.exc_info()[2]):
fname, lineno, fn, text = frame
ekm_log("Error in %s on line %d" % (fname, lineno))
return False
except TypeError:
ekm_log(str(sys.exc_info()))
for frame in traceback.extract_tb(sys.exc_info()[2]):
fname, lineno, fn, text = frame
ekm_log("Error in %s on line %d" % (fname, lineno))
return False
except ValueError:
ekm_log(str(sys.exc_info()))
for frame in traceback.extract_tb(sys.exc_info()[2]):
fname, lineno, fn, text = frame
ekm_log("Error in %s on line %d" % (fname, lineno))
return False
return False
|
python
|
{
"resource": ""
}
|
q275988
|
Meter.splitEkmDate
|
test
|
def splitEkmDate(dateint):
"""Break out a date from Omnimeter read.
Note a corrupt date will raise an exception when you
convert it to int to hand to this method.
Args:
dateint (int): Omnimeter datetime as int.
Returns:
tuple: Named tuple which breaks out as followws:
========== =====================
yy Last 2 digits of year
mm Month 1-12
dd Day 1-31
weekday Zero based weekday
hh Hour 0-23
minutes Minutes 0-59
ss Seconds 0-59
========== =====================
"""
date_str = str(dateint)
dt = namedtuple('EkmDate', ['yy', 'mm', 'dd', 'weekday', 'hh', 'minutes', 'ss'])
if len(date_str) != 14:
dt.yy = dt.mm = dt.dd = dt.weekday = dt.hh = dt.minutes = dt.ss = 0
return dt
dt.yy = int(date_str[0:2])
dt.mm = int(date_str[2:4])
dt.dd = int(date_str[4:6])
dt.weekday = int(date_str[6:8])
dt.hh = int(date_str[8:10])
dt.minutes = int(date_str[10:12])
dt.ss = int(date_str[12:14])
return dt
|
python
|
{
"resource": ""
}
|
q275989
|
Meter.getMonthsBuffer
|
test
|
def getMonthsBuffer(self, direction):
""" Get the months tariff SerialBlock for meter.
Args:
direction (int): A :class:`~ekmmeters.ReadMonths` value.
Returns:
SerialBlock: Requested months tariffs buffer.
"""
if direction == ReadMonths.kWhReverse:
return self.m_rev_mons
# default direction == ReadMonths.kWh
return self.m_mons
|
python
|
{
"resource": ""
}
|
q275990
|
Meter.setCTRatio
|
test
|
def setCTRatio(self, new_ct, password="00000000"):
""" Serial call to set CT ratio for attached inductive pickup.
Args:
new_ct (int): A :class:`~ekmmeters.CTRatio` value, a legal amperage setting.
password (str): Optional password.
Returns:
bool: True on completion with ACK.
"""
ret = False
self.setContext("setCTRatio")
try:
self.clearCmdMsg()
if ((new_ct != CTRatio.Amps_100) and (new_ct != CTRatio.Amps_200) and
(new_ct != CTRatio.Amps_400) and (new_ct != CTRatio.Amps_600) and
(new_ct != CTRatio.Amps_800) and (new_ct != CTRatio.Amps_1000) and
(new_ct != CTRatio.Amps_1200) and (new_ct != CTRatio.Amps_1500) and
(new_ct != CTRatio.Amps_2000) and (new_ct != CTRatio.Amps_3000) and
(new_ct != CTRatio.Amps_4000) and (new_ct != CTRatio.Amps_5000)):
self.writeCmdMsg("Legal CT Ratios: 100, 200, 400, 600, " +
"800, 1000, 1200, 1500, 2000, 3000, 4000 and 5000")
self.setContext("")
return ret
if len(password) != 8:
self.writeCmdMsg("Invalid password length.")
self.setContext("")
return ret
if not self.request(False):
self.writeCmdMsg("Bad read CRC on setting")
else:
if not self.serialCmdPwdAuth(password):
self.writeCmdMsg("Password failure")
else:
req_str = "015731023030443028" + binascii.hexlify(str(new_ct).zfill(4)) + "2903"
req_str += self.calc_crc16(req_str[2:].decode("hex"))
self.m_serial_port.write(req_str.decode("hex"))
if self.m_serial_port.getResponse(self.getContext()).encode("hex") == "06":
self.writeCmdMsg("Success(setCTRatio): 06 returned.")
ret = True
self.serialPostEnd()
except:
ekm_log(traceback.format_exc(sys.exc_info()))
self.setContext("")
return ret
|
python
|
{
"resource": ""
}
|
q275991
|
Meter.assignSchedule
|
test
|
def assignSchedule(self, schedule, period, hour, minute, tariff):
""" Assign one schedule tariff period to meter bufffer.
Args:
schedule (int): A :class:`~ekmmeters.Schedules` value or in range(Extents.Schedules).
tariff (int): :class:`~ekmmeters.Tariffs` value or in range(Extents.Tariffs).
hour (int): Hour from 0-23.
minute (int): Minute from 0-59.
tariff (int): Rate value.
Returns:
bool: True on completed assignment.
"""
if ((schedule not in range(Extents.Schedules)) or
(period not in range(Extents.Tariffs)) or
(hour < 0) or (hour > 23) or (minute < 0) or
(minute > 59) or (tariff < 0)):
ekm_log("Out of bounds in Schedule_" + str(schedule + 1))
return False
period += 1
idx_min = "Min_" + str(period)
idx_hour = "Hour_" + str(period)
idx_rate = "Tariff_" + str(period)
if idx_min not in self.m_schedule_params:
ekm_log("Incorrect index: " + idx_min)
return False
if idx_hour not in self.m_schedule_params:
ekm_log("Incorrect index: " + idx_hour)
return False
if idx_rate not in self.m_schedule_params:
ekm_log("Incorrect index: " + idx_rate)
return False
self.m_schedule_params[idx_rate] = tariff
self.m_schedule_params[idx_hour] = hour
self.m_schedule_params[idx_min] = minute
self.m_schedule_params['Schedule'] = schedule
return True
|
python
|
{
"resource": ""
}
|
q275992
|
Meter.assignSeasonSchedule
|
test
|
def assignSeasonSchedule(self, season, month, day, schedule):
""" Define a single season and assign a schedule
Args:
season (int): A :class:`~ekmmeters.Seasons` value or in range(Extent.Seasons).
month (int): Month 1-12.
day (int): Day 1-31.
schedule (int): A :class:`~ekmmeters.LCDItems` value or in range(Extent.Schedules).
Returns:
bool: True on completion and ACK.
"""
season += 1
schedule += 1
if ((season < 1) or (season > Extents.Seasons) or (schedule < 1) or
(schedule > Extents.Schedules) or (month > 12) or (month < 0) or
(day < 0) or (day > 31)):
ekm_log("Out of bounds: month " + str(month) + " day " + str(day) +
" schedule " + str(schedule) + " season " + str(season))
return False
idx_mon = "Season_" + str(season) + "_Start_Day"
idx_day = "Season_" + str(season) + "_Start_Month"
idx_schedule = "Season_" + str(season) + "_Schedule"
if idx_mon not in self.m_seasons_sched_params:
ekm_log("Incorrect index: " + idx_mon)
return False
if idx_day not in self.m_seasons_sched_params:
ekm_log("Incorrect index: " + idx_day)
return False
if idx_schedule not in self.m_seasons_sched_params:
ekm_log("Incorrect index: " + idx_schedule)
return False
self.m_seasons_sched_params[idx_mon] = month
self.m_seasons_sched_params[idx_day] = day
self.m_seasons_sched_params[idx_schedule] = schedule
return True
|
python
|
{
"resource": ""
}
|
q275993
|
Meter.setSeasonSchedules
|
test
|
def setSeasonSchedules(self, cmd_dict=None, password="00000000"):
""" Serial command to set seasons table.
If no dictionary is passed, the meter object buffer is used.
Args:
cmd_dict (dict): Optional dictionary of season schedules.
password (str): Optional password
Returns:
bool: True on completion and ACK.
"""
result = False
self.setContext("setSeasonSchedules")
if not cmd_dict:
cmd_dict = self.m_seasons_sched_params
try:
if not self.request(False):
self.writeCmdMsg("Bad read CRC on setting")
else:
if not self.serialCmdPwdAuth(password):
self.writeCmdMsg("Password failure")
else:
req_table = ""
req_table += binascii.hexlify(str(cmd_dict["Season_1_Start_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_1_Start_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_1_Schedule"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_2_Start_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_2_Start_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_2_Schedule"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_3_Start_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_3_Start_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_3_Schedule"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_4_Start_Month"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_4_Start_Day"]).zfill(2))
req_table += binascii.hexlify(str(cmd_dict["Season_4_Schedule"]).zfill(2))
req_table += binascii.hexlify(str(0).zfill(24))
req_str = "015731023030383028" + req_table + "2903"
req_str += self.calc_crc16(req_str[2:].decode("hex"))
self.m_serial_port.write(req_str.decode("hex"))
if self.m_serial_port.getResponse(self.getContext()).encode("hex") == "06":
self.writeCmdMsg("Success(setSeasonSchedules): 06 returned.")
result = True
self.serialPostEnd()
except:
ekm_log(traceback.format_exc(sys.exc_info()))
self.setContext("")
return result
|
python
|
{
"resource": ""
}
|
q275994
|
Meter.assignHolidayDate
|
test
|
def assignHolidayDate(self, holiday, month, day):
""" Set a singe holiday day and month in object buffer.
There is no class style enum for holidays.
Args:
holiday (int): 0-19 or range(Extents.Holidays).
month (int): Month 1-12.
day (int): Day 1-31
Returns:
bool: True on completion.
"""
holiday += 1
if (month > 12) or (month < 0) or (day > 31) or (day < 0) or (holiday < 1) or (holiday > Extents.Holidays):
ekm_log("Out of bounds: month " + str(month) + " day " + str(day) + " holiday " + str(holiday))
return False
day_str = "Holiday_" + str(holiday) + "_Day"
mon_str = "Holiday_" + str(holiday) + "_Month"
if day_str not in self.m_holiday_date_params:
ekm_log("Incorrect index: " + day_str)
return False
if mon_str not in self.m_holiday_date_params:
ekm_log("Incorrect index: " + mon_str)
return False
self.m_holiday_date_params[day_str] = day
self.m_holiday_date_params[mon_str] = month
return True
|
python
|
{
"resource": ""
}
|
q275995
|
Meter.readSchedules
|
test
|
def readSchedules(self, tableset):
""" Serial call to read schedule tariffs buffer
Args:
tableset (int): :class:`~ekmmeters.ReadSchedules` buffer to return.
Returns:
bool: True on completion and ACK.
"""
self.setContext("readSchedules")
try:
req_table = binascii.hexlify(str(tableset).zfill(1))
req_str = "01523102303037" + req_table + "282903"
self.request(False)
req_crc = self.calc_crc16(req_str[2:].decode("hex"))
req_str += req_crc
self.m_serial_port.write(req_str.decode("hex"))
raw_ret = self.m_serial_port.getResponse(self.getContext())
self.serialPostEnd()
return_crc = self.calc_crc16(raw_ret[1:-2])
if tableset == ReadSchedules.Schedules_1_To_4:
unpacked_read = self.unpackStruct(raw_ret, self.m_schd_1_to_4)
self.convertData(unpacked_read, self.m_schd_1_to_4, self.m_kwh_precision)
if str(return_crc) == str(self.m_schd_1_to_4["crc16"][MeterData.StringValue]):
ekm_log("Schedules 1 to 4 CRC success (06 return")
self.setContext("")
return True
elif tableset == ReadSchedules.Schedules_5_To_6:
unpacked_read = self.unpackStruct(raw_ret, self.m_schd_5_to_6)
self.convertData(unpacked_read, self.m_schd_5_to_6, self.m_kwh_precision)
if str(return_crc) == str(self.m_schd_5_to_6["crc16"][MeterData.StringValue]):
ekm_log("Schedules 5 to 8 CRC success (06 return)")
self.setContext("")
return True
except:
ekm_log(traceback.format_exc(sys.exc_info()))
self.setContext("")
return False
|
python
|
{
"resource": ""
}
|
q275996
|
Meter.extractSchedule
|
test
|
def extractSchedule(self, schedule, period):
""" Read a single schedule tariff from meter object buffer.
Args:
schedule (int): A :class:`~ekmmeters.Schedules` value or in range(Extent.Schedules).
tariff (int): A :class:`~ekmmeters.Tariffs` value or in range(Extent.Tariffs).
Returns:
bool: True on completion.
"""
ret = namedtuple("ret", ["Hour", "Min", "Tariff", "Period", "Schedule"])
work_table = self.m_schd_1_to_4
if Schedules.Schedule_5 <= schedule <= Schedules.Schedule_6:
work_table = self.m_schd_5_to_6
period += 1
schedule += 1
ret.Period = str(period)
ret.Schedule = str(schedule)
if (schedule < 1) or (schedule > Extents.Schedules) or (period < 0) or (period > Extents.Periods):
ekm_log("Out of bounds: tariff " + str(period) + " for schedule " + str(schedule))
ret.Hour = ret.Min = ret.Tariff = str(0)
return ret
idxhr = "Schedule_" + str(schedule) + "_Period_" + str(period) + "_Hour"
idxmin = "Schedule_" + str(schedule) + "_Period_" + str(period) + "_Min"
idxrate = "Schedule_" + str(schedule) + "_Period_" + str(period) + "_Tariff"
if idxhr not in work_table:
ekm_log("Incorrect index: " + idxhr)
ret.Hour = ret.Min = ret.Tariff = str(0)
return ret
if idxmin not in work_table:
ekm_log("Incorrect index: " + idxmin)
ret.Hour = ret.Min = ret.Tariff = str(0)
return ret
if idxrate not in work_table:
ekm_log("Incorrect index: " + idxrate)
ret.Hour = ret.Min = ret.Tariff = str(0)
return ret
ret.Hour = work_table[idxhr][MeterData.StringValue]
ret.Min = work_table[idxmin][MeterData.StringValue].zfill(2)
ret.Tariff = work_table[idxrate][MeterData.StringValue]
return ret
|
python
|
{
"resource": ""
}
|
q275997
|
Meter.readMonthTariffs
|
test
|
def readMonthTariffs(self, months_type):
""" Serial call to read month tariffs block into meter object buffer.
Args:
months_type (int): A :class:`~ekmmeters.ReadMonths` value.
Returns:
bool: True on completion.
"""
self.setContext("readMonthTariffs")
try:
req_type = binascii.hexlify(str(months_type).zfill(1))
req_str = "01523102303031" + req_type + "282903"
work_table = self.m_mons
if months_type == ReadMonths.kWhReverse:
work_table = self.m_rev_mons
self.request(False)
req_crc = self.calc_crc16(req_str[2:].decode("hex"))
req_str += req_crc
self.m_serial_port.write(req_str.decode("hex"))
raw_ret = self.m_serial_port.getResponse(self.getContext())
self.serialPostEnd()
unpacked_read = self.unpackStruct(raw_ret, work_table)
self.convertData(unpacked_read, work_table, self.m_kwh_precision)
return_crc = self.calc_crc16(raw_ret[1:-2])
if str(return_crc) == str(work_table["crc16"][MeterData.StringValue]):
ekm_log("Months CRC success, type = " + str(req_type))
self.setContext("")
return True
except:
ekm_log(traceback.format_exc(sys.exc_info()))
self.setContext("")
return False
|
python
|
{
"resource": ""
}
|
q275998
|
Meter.extractMonthTariff
|
test
|
def extractMonthTariff(self, month):
""" Extract the tariff for a single month from the meter object buffer.
Args:
month (int): A :class:`~ekmmeters.Months` value or range(Extents.Months).
Returns:
tuple: The eight tariff period totals for month. The return tuple breaks out as follows:
================= ======================================
kWh_Tariff_1 kWh for tariff period 1 over month.
kWh_Tariff_2 kWh for tariff period 2 over month
kWh_Tariff_3 kWh for tariff period 3 over month
kWh_Tariff_4 kWh for tariff period 4 over month
kWh_Tot Total kWh over requested month
Rev_kWh_Tariff_1 Rev kWh for tariff period 1 over month
Rev_kWh_Tariff_3 Rev kWh for tariff period 2 over month
Rev_kWh_Tariff_3 Rev kWh for tariff period 3 over month
Rev_kWh_Tariff_4 Rev kWh for tariff period 4 over month
Rev_kWh_Tot Total Rev kWh over requested month
================= ======================================
"""
ret = namedtuple("ret", ["Month", Field.kWh_Tariff_1, Field.kWh_Tariff_2, Field.kWh_Tariff_3,
Field.kWh_Tariff_4, Field.kWh_Tot, Field.Rev_kWh_Tariff_1,
Field.Rev_kWh_Tariff_2, Field.Rev_kWh_Tariff_3,
Field.Rev_kWh_Tariff_4, Field.Rev_kWh_Tot])
month += 1
ret.Month = str(month)
if (month < 1) or (month > Extents.Months):
ret.kWh_Tariff_1 = ret.kWh_Tariff_2 = ret.kWh_Tariff_3 = ret.kWh_Tariff_4 = str(0)
ret.Rev_kWh_Tariff_1 = ret.Rev_kWh_Tariff_2 = ret.Rev_kWh_Tariff_3 = ret.Rev_kWh_Tariff_4 = str(0)
ret.kWh_Tot = ret.Rev_kWh_Tot = str(0)
ekm_log("Out of range(Extents.Months) month = " + str(month))
return ret
base_str = "Month_" + str(month) + "_"
ret.kWh_Tariff_1 = self.m_mons[base_str + "Tariff_1"][MeterData.StringValue]
ret.kWh_Tariff_2 = self.m_mons[base_str + "Tariff_2"][MeterData.StringValue]
ret.kWh_Tariff_3 = self.m_mons[base_str + "Tariff_3"][MeterData.StringValue]
ret.kWh_Tariff_4 = self.m_mons[base_str + "Tariff_4"][MeterData.StringValue]
ret.kWh_Tot = self.m_mons[base_str + "Tot"][MeterData.StringValue]
ret.Rev_kWh_Tariff_1 = self.m_rev_mons[base_str + "Tariff_1"][MeterData.StringValue]
ret.Rev_kWh_Tariff_2 = self.m_rev_mons[base_str + "Tariff_2"][MeterData.StringValue]
ret.Rev_kWh_Tariff_3 = self.m_rev_mons[base_str + "Tariff_3"][MeterData.StringValue]
ret.Rev_kWh_Tariff_4 = self.m_rev_mons[base_str + "Tariff_4"][MeterData.StringValue]
ret.Rev_kWh_Tot = self.m_rev_mons[base_str + "Tot"][MeterData.StringValue]
return ret
|
python
|
{
"resource": ""
}
|
q275999
|
Meter.readHolidayDates
|
test
|
def readHolidayDates(self):
""" Serial call to read holiday dates into meter object buffer.
Returns:
bool: True on completion.
"""
self.setContext("readHolidayDates")
try:
req_str = "0152310230304230282903"
self.request(False)
req_crc = self.calc_crc16(req_str[2:].decode("hex"))
req_str += req_crc
self.m_serial_port.write(req_str.decode("hex"))
raw_ret = self.m_serial_port.getResponse(self.getContext())
self.serialPostEnd()
unpacked_read = self.unpackStruct(raw_ret, self.m_hldy)
self.convertData(unpacked_read, self.m_hldy, self.m_kwh_precision)
return_crc = self.calc_crc16(raw_ret[1:-2])
if str(return_crc) == str(self.m_hldy["crc16"][MeterData.StringValue]):
ekm_log("Holidays and Schedules CRC success")
self.setContext("")
return True
except:
ekm_log(traceback.format_exc(sys.exc_info()))
self.setContext("")
return False
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.