_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q256800
HandleConsentEnrollment.get
validation
def get(self, request, enterprise_uuid, course_id): """ Handle the enrollment of enterprise learner in the provided course. Based on `enterprise_uuid` in URL, the view will decide which enterprise customer's course enrollment record should be created. Depending on the value of query parameter `course_mode` then learner will be either redirected to LMS dashboard for audit modes or redirected to ecommerce basket flow for payment of premium modes. """ enrollment_course_mode = request.GET.get('course_mode') enterprise_catalog_uuid = request.GET.get('catalog') # Redirect the learner to LMS dashboard in case no course mode is # provided as query parameter `course_mode` if not enrollment_course_mode: return redirect(LMS_DASHBOARD_URL) enrollment_api_client = EnrollmentApiClient() course_modes = enrollment_api_client.get_course_modes(course_id) # Verify that the request user belongs to the enterprise against the # provided `enterprise_uuid`. enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid) enterprise_customer_user = get_enterprise_customer_user(request.user.id, enterprise_customer.uuid) if not course_modes: context_data = get_global_context(request, enterprise_customer) error_code = 'ENTHCE000' log_message = ( 'No course_modes for course_id {course_id} for enterprise_catalog_uuid ' '{enterprise_catalog_uuid}.' 'The following error was presented to ' 'user {userid}: {error_code}'.format( userid=request.user.id, enterprise_catalog_uuid=enterprise_catalog_uuid, course_id=course_id, error_code=error_code ) ) return render_page_with_error_code_message(request, context_data, error_code, log_message) selected_course_mode = None for course_mode in course_modes: if course_mode['slug'] == enrollment_course_mode: selected_course_mode = course_mode break if not selected_course_mode: return redirect(LMS_DASHBOARD_URL) # Create the Enterprise backend database records for this course # enrollment
python
{ "resource": "" }
q256801
CourseEnrollmentView.set_final_prices
validation
def set_final_prices(self, modes, request): """ Set the final discounted price on each premium mode. """ result = [] for mode in modes: if mode['premium']: mode['final_price'] = EcommerceApiClient(request.user).get_course_final_price( mode=mode,
python
{ "resource": "" }
q256802
CourseEnrollmentView.get_available_course_modes
validation
def get_available_course_modes(self, request, course_run_id, enterprise_catalog): """ Return the available course modes for the course run. The provided EnterpriseCustomerCatalog is used to filter and order the course modes returned using the EnterpriseCustomerCatalog's field "enabled_course_modes". """ modes = EnrollmentApiClient().get_course_modes(course_run_id) if not modes: LOGGER.warning('Unable to get course modes for course run id {course_run_id}.'.format( course_run_id=course_run_id )) messages.add_generic_info_message_for_error(request) if enterprise_catalog: # filter and order course modes according to the enterprise catalog modes = [mode for
python
{ "resource": "" }
q256803
CourseEnrollmentView.get
validation
def get(self, request, enterprise_uuid, course_id): """ Show course track selection page for the enterprise. Based on `enterprise_uuid` in URL, the view will decide which enterprise customer's course enrollment page is to use. Unauthenticated learners will be redirected to enterprise-linked SSO. A 404 will be raised if any of the following conditions are met: * No enterprise customer uuid kwarg `enterprise_uuid` in request. * No enterprise customer found against the enterprise customer uuid `enterprise_uuid` in the request kwargs. * No course is found in database against the provided `course_id`. """ # Check to see if access to the course run is restricted for this user. embargo_url = EmbargoApiClient.redirect_if_blocked([course_id], request.user, get_ip(request), request.path) if embargo_url: return redirect(embargo_url) enterprise_customer, course, course_run, modes = self.get_base_details( request, enterprise_uuid, course_id ) enterprise_customer_user = get_enterprise_customer_user(request.user.id, enterprise_uuid) data_sharing_consent = DataSharingConsent.objects.proxied_get( username=enterprise_customer_user.username, course_id=course_id, enterprise_customer=enterprise_customer ) enrollment_client = EnrollmentApiClient() enrolled_course = enrollment_client.get_course_enrollment(request.user.username, course_id) try: enterprise_course_enrollment =
python
{ "resource": "" }
q256804
ProgramEnrollmentView.extend_course
validation
def extend_course(course, enterprise_customer, request): """ Extend a course with more details needed for the program landing page. In particular, we add the following: * `course_image_uri` * `course_title` * `course_level_type` * `course_short_description` * `course_full_description` * `course_effort` * `expected_learning_items` * `staff` """ course_run_id = course['course_runs'][0]['key'] try: catalog_api_client = CourseCatalogApiServiceClient(enterprise_customer.site) except ImproperlyConfigured: error_code = 'ENTPEV000' LOGGER.error( 'CourseCatalogApiServiceClient is improperly configured. ' 'Returned error code {error_code} to user {userid} ' 'and enterprise_customer {enterprise_customer} ' 'for course_run_id {course_run_id}'.format( error_code=error_code, userid=request.user.id, enterprise_customer=enterprise_customer.uuid, course_run_id=course_run_id, ) ) messages.add_generic_error_message_with_code(request, error_code) return ({}, error_code) course_details, course_run_details = catalog_api_client.get_course_and_course_run(course_run_id) if not course_details or not course_run_details: error_code = 'ENTPEV001' LOGGER.error( 'User {userid} of enterprise customer {enterprise_customer} encountered an error.' 'No course_details or course_run_details found for ' 'course_run_id {course_run_id}. ' 'The following error code reported to the user: {error_code}'.format( userid=request.user.id, enterprise_customer=enterprise_customer.uuid, course_run_id=course_run_id, error_code=error_code, ) ) messages.add_generic_error_message_with_code(request, error_code) return ({}, error_code) weeks_to_complete = course_run_details['weeks_to_complete']
python
{ "resource": "" }
q256805
ProgramEnrollmentView.get
validation
def get(self, request, enterprise_uuid, program_uuid): """ Show Program Landing page for the Enterprise's Program. Render the Enterprise's Program Enrollment page for a specific program. The Enterprise and Program are both selected by their respective UUIDs. Unauthenticated learners will be redirected to enterprise-linked SSO. A 404 will be raised if any of the following conditions are met: * No enterprise customer UUID query parameter ``enterprise_uuid`` found in request. * No enterprise customer found against the enterprise customer uuid ``enterprise_uuid`` in the request kwargs. * No Program can be found given ``program_uuid`` either at all or associated with the Enterprise.. """ verify_edx_resources() enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid) context_data = get_global_context(request, enterprise_customer) program_details, error_code = self.get_program_details(request, program_uuid, enterprise_customer) if error_code: return render( request, ENTERPRISE_GENERAL_ERROR_PAGE, context=context_data, status=404, ) if
python
{ "resource": "" }
q256806
RouterView.get_path_variables
validation
def get_path_variables(**kwargs): """ Get the base variables for any view to route to. Currently gets: - `enterprise_uuid` - the UUID of the enterprise customer. - `course_run_id` - the ID of the course, if applicable. - `program_uuid` - the UUID of the program, if applicable. """ enterprise_customer_uuid
python
{ "resource": "" }
q256807
RouterView.get_course_run_id
validation
def get_course_run_id(user, enterprise_customer, course_key): """ User is requesting a course, we need to translate that into the current course run. :param user: :param enterprise_customer: :param course_key: :return: course_run_id """ try: course = CourseCatalogApiServiceClient(enterprise_customer.site).get_course_details(course_key)
python
{ "resource": "" }
q256808
RouterView.eligible_for_direct_audit_enrollment
validation
def eligible_for_direct_audit_enrollment(self, request, enterprise_customer, resource_id, course_key=None): """ Return whether a request is eligible for direct audit enrollment for a particular enterprise customer. 'resource_id' can be either course_run_id or program_uuid. We check for the following criteria: - The `audit` query parameter. - The user's being routed to the course enrollment landing page. - The customer's catalog contains the course in question. - The audit track is an available mode for the course. """ course_identifier = course_key if course_key else resource_id # Return
python
{ "resource": "" }
q256809
RouterView.redirect
validation
def redirect(self, request, *args, **kwargs): """ Redirects to the appropriate view depending on where the user came from. """ enterprise_customer_uuid, course_run_id, course_key, program_uuid = RouterView.get_path_variables(**kwargs) resource_id = course_key or course_run_id or program_uuid # Replace enterprise UUID and resource ID with '{}', to easily match with a path in RouterView.VIEWS. Example: # /enterprise/fake-uuid/course/course-v1:cool+course+2017/enroll/ -> /enterprise/{}/course/{}/enroll/
python
{ "resource": "" }
q256810
RouterView.get
validation
def get(self, request, *args, **kwargs): """ Run some custom GET logic for Enterprise workflows before routing the user through existing views. In particular, before routing to existing views: - If the requested resource is a course, find the current course run for that course, and make that course run the requested resource instead. - Look to see whether a request is eligible for direct audit enrollment, and if so, directly enroll the user. """ enterprise_customer_uuid, course_run_id, course_key, program_uuid = RouterView.get_path_variables(**kwargs) enterprise_customer = get_enterprise_customer_or_404(enterprise_customer_uuid) if course_key: try: course_run_id = RouterView.get_course_run_id(request.user, enterprise_customer, course_key) except Http404: context_data = get_global_context(request, enterprise_customer) error_code = 'ENTRV000' log_message = ( 'Could not find course run with id {course_run_id} ' 'for course key {course_key} and program_uuid {program_uuid} ' 'for enterprise_customer_uuid {enterprise_customer_uuid} ' 'Returned error code {error_code} to user {userid}'.format( course_key=course_key, course_run_id=course_run_id, enterprise_customer_uuid=enterprise_customer_uuid, error_code=error_code, userid=request.user.id, program_uuid=program_uuid, ) ) return render_page_with_error_code_message(request, context_data, error_code, log_message) kwargs['course_id'] = course_run_id # Ensure that the link is saved to the database prior to making some call in a downstream view # which may need to know that the user belongs to an enterprise customer.
python
{ "resource": "" }
q256811
RouterView.post
validation
def post(self, request, *args, **kwargs): """ Run some custom POST logic for Enterprise workflows before routing the user through existing views. """ # pylint: disable=unused-variable enterprise_customer_uuid, course_run_id, course_key, program_uuid = RouterView.get_path_variables(**kwargs) enterprise_customer = get_enterprise_customer_or_404(enterprise_customer_uuid) if course_key: context_data = get_global_context(request, enterprise_customer) try: kwargs['course_id'] = RouterView.get_course_run_id(request.user, enterprise_customer, course_key) except Http404: error_code = 'ENTRV001' log_message = ( 'Could not find course run with id {course_run_id} ' 'for course key {course_key} and ' 'for enterprise_customer_uuid {enterprise_customer_uuid} '
python
{ "resource": "" }
q256812
transmit_content_metadata
validation
def transmit_content_metadata(username, channel_code, channel_pk): """ Task to send content metadata to each linked integrated channel. Arguments: username (str): The username of the User to be used for making API requests to retrieve content metadata. channel_code (str): Capitalized identifier for the integrated channel. channel_pk (str): Primary key for identifying integrated channel. """ start = time.time() api_user = User.objects.get(username=username)
python
{ "resource": "" }
q256813
transmit_learner_data
validation
def transmit_learner_data(username, channel_code, channel_pk): """ Task to send learner data to each linked integrated channel. Arguments: username (str): The username of the User to be used for making API requests for learner data. channel_code (str): Capitalized identifier for the integrated channel channel_pk (str): Primary key for identifying integrated channel """ start = time.time() api_user = User.objects.get(username=username) integrated_channel = INTEGRATED_CHANNEL_CHOICES[channel_code].objects.get(pk=channel_pk) LOGGER.info('Processing learners for integrated channel using configuration: [%s]', integrated_channel) # Note: learner data
python
{ "resource": "" }
q256814
unlink_inactive_learners
validation
def unlink_inactive_learners(channel_code, channel_pk): """ Task to unlink inactive learners of provided integrated channel. Arguments: channel_code (str): Capitalized identifier for the integrated channel channel_pk (str): Primary key for identifying integrated channel """ start = time.time() integrated_channel = INTEGRATED_CHANNEL_CHOICES[channel_code].objects.get(pk=channel_pk) LOGGER.info('Processing learners to unlink inactive users using configuration: [%s]', integrated_channel) # Note: learner data transmission code paths don't raise any uncaught exception, so we don't need a
python
{ "resource": "" }
q256815
handle_user_post_save
validation
def handle_user_post_save(sender, **kwargs): # pylint: disable=unused-argument """ Handle User model changes - checks if pending enterprise customer user record exists and upgrades it to actual link. If there are pending enrollments attached to the PendingEnterpriseCustomerUser, then this signal also takes the newly-created users and enrolls them in the relevant courses. """ created = kwargs.get("created", False) user_instance = kwargs.get("instance", None) if user_instance is None: return # should never happen, but better safe than 500 error try: pending_ecu = PendingEnterpriseCustomerUser.objects.get(user_email=user_instance.email) except PendingEnterpriseCustomerUser.DoesNotExist: return # nothing to do in this case if not created: # existing user changed his email to match one of pending link records - try linking him to EC try: existing_record = EnterpriseCustomerUser.objects.get(user_id=user_instance.id) message_template = "User {user} have changed email to match pending Enterprise Customer link, " \ "but was already linked to Enterprise Customer {enterprise_customer} - " \ "deleting pending link record" logger.info(message_template.format( user=user_instance, enterprise_customer=existing_record.enterprise_customer )) pending_ecu.delete()
python
{ "resource": "" }
q256816
default_content_filter
validation
def default_content_filter(sender, instance, **kwargs): # pylint: disable=unused-argument """ Set default value for `EnterpriseCustomerCatalog.content_filter` if
python
{ "resource": "" }
q256817
assign_enterprise_learner_role
validation
def assign_enterprise_learner_role(sender, instance, **kwargs): # pylint: disable=unused-argument """ Assign an enterprise learner role to EnterpriseCustomerUser whenever a new record is created. """ if kwargs['created'] and instance.user:
python
{ "resource": "" }
q256818
delete_enterprise_learner_role_assignment
validation
def delete_enterprise_learner_role_assignment(sender, instance, **kwargs): # pylint: disable=unused-argument """ Delete the associated enterprise learner role assignment record when deleting an EnterpriseCustomerUser record. """ if instance.user: enterprise_learner_role, __ = SystemWideEnterpriseRole.objects.get_or_create(name=ENTERPRISE_LEARNER_ROLE) try: SystemWideEnterpriseUserRoleAssignment.objects.get(
python
{ "resource": "" }
q256819
enterprise_customer_required
validation
def enterprise_customer_required(view): """ Ensure the user making the API request is associated with an EnterpriseCustomer. This decorator attempts to find an EnterpriseCustomer associated with the requesting user and passes that EnterpriseCustomer to the view as a parameter. It will return a PermissionDenied error if an EnterpriseCustomer cannot be found. Usage:: @enterprise_customer_required() def my_view(request, enterprise_customer): # Some functionality ... OR class MyView(View): ...
python
{ "resource": "" }
q256820
require_at_least_one_query_parameter
validation
def require_at_least_one_query_parameter(*query_parameter_names): """ Ensure at least one of the specified query parameters are included in the request. This decorator checks for the existence of at least one of the specified query parameters and passes the values as function parameters to the decorated view. If none of the specified query parameters are included in the request, a ValidationError is raised. Usage:: @require_at_least_one_query_parameter('program_uuids', 'course_run_ids') def my_view(request, program_uuids, course_run_ids): # Some functionality ... """ def outer_wrapper(view): """ Allow the passing of parameters to require_at_least_one_query_parameter. """ @wraps(view) def wrapper(request, *args, **kwargs): """ Checks for the existence of the specified query parameters, raises a ValidationError if none of them were included in the request. """ requirement_satisfied = False for query_parameter_name in query_parameter_names: query_parameter_values = request.query_params.getlist(query_parameter_name)
python
{ "resource": "" }
q256821
Command._get_enterprise_customer_users_batch
validation
def _get_enterprise_customer_users_batch(self, start, end): """ Returns a batched queryset of EnterpriseCustomerUser objects. """ LOGGER.info('Fetching
python
{ "resource": "" }
q256822
Command._assign_enterprise_role_to_users
validation
def _assign_enterprise_role_to_users(self, _get_batch_method, options, is_feature_role=False): """ Assigns enterprise role to users. """ role_name = options['role'] batch_limit = options['batch_limit'] batch_sleep = options['batch_sleep'] batch_offset = options['batch_offset'] current_batch_index = batch_offset users_batch = _get_batch_method( batch_offset, batch_offset + batch_limit ) role_class = SystemWideEnterpriseRole role_assignment_class = SystemWideEnterpriseUserRoleAssignment
python
{ "resource": "" }
q256823
Command.handle
validation
def handle(self, *args, **options): """ Entry point for managment command execution. """ LOGGER.info('Starting assigning enterprise roles to users!') role = options['role'] if role == ENTERPRISE_ADMIN_ROLE: # Assign admin role to non-staff users with enterprise data api access. self._assign_enterprise_role_to_users(self._get_enterprise_admin_users_batch, options) elif role == ENTERPRISE_OPERATOR_ROLE: # Assign operator role to staff users with enterprise data api access. self._assign_enterprise_role_to_users(self._get_enterprise_operator_users_batch, options) elif role == ENTERPRISE_LEARNER_ROLE: # Assign enterprise learner role to enterprise customer users. self._assign_enterprise_role_to_users(self._get_enterprise_customer_users_batch, options) elif role == ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE: # Assign enterprise enrollment api admin to non-staff users with enterprise data api access.
python
{ "resource": "" }
q256824
DegreedLearnerTransmitter.transmit
validation
def transmit(self, payload, **kwargs): """ Send a completion status call to Degreed using the client. Args: payload: The learner completion data payload to send
python
{ "resource": "" }
q256825
get_enterprise_customer_for_running_pipeline
validation
def get_enterprise_customer_for_running_pipeline(request, pipeline): # pylint: disable=invalid-name """ Get the EnterpriseCustomer associated with a running pipeline. """ sso_provider_id = request.GET.get('tpa_hint')
python
{ "resource": "" }
q256826
handle_enterprise_logistration
validation
def handle_enterprise_logistration(backend, user, **kwargs): """ Perform the linking of user in the process of logging to the Enterprise Customer. Args: backend: The class handling the SSO interaction (SAML, OAuth, etc) user: The user object in the process of being logged in with **kwargs: Any remaining pipeline variables """ request = backend.strategy.request enterprise_customer = get_enterprise_customer_for_running_pipeline( request, { 'backend': backend.name, 'kwargs': kwargs } ) if enterprise_customer is None:
python
{ "resource": "" }
q256827
get_user_from_social_auth
validation
def get_user_from_social_auth(tpa_provider, tpa_username): """ Find the LMS user from the LMS model `UserSocialAuth`. Arguments: tpa_provider (third_party_auth.provider): third party auth provider object tpa_username (str): Username returned by the third party auth
python
{ "resource": "" }
q256828
SAPSuccessFactorsAPIClient._create_session
validation
def _create_session(self): """ Instantiate a new session object for use in connecting with SAP SuccessFactors """ session = requests.Session() session.timeout = self.SESSION_TIMEOUT oauth_access_token, expires_at = SAPSuccessFactorsAPIClient.get_oauth_access_token( self.enterprise_configuration.sapsf_base_url,
python
{ "resource": "" }
q256829
SAPSuccessFactorsAPIClient.create_course_completion
validation
def create_course_completion(self, user_id, payload): """ Send a completion status payload to the SuccessFactors OCN Completion Status endpoint Args: user_id (str): The sap user id that the completion status is being sent for. payload (str): JSON encoded object (serialized from SapSuccessFactorsLearnerDataTransmissionAudit) containing completion status fields per SuccessFactors documentation. Returns: The body of the response from SAP SuccessFactors, if successful Raises:
python
{ "resource": "" }
q256830
SAPSuccessFactorsAPIClient._call_post_with_user_override
validation
def _call_post_with_user_override(self, sap_user_id, url, payload): """ Make a post request with an auth token acquired for a specific user to a SuccessFactors endpoint. Args: sap_user_id (str): The user to use to retrieve an auth token. url (str): The url to post to. payload (str): The json encoded payload to post. """ SAPSuccessFactorsEnterpriseCustomerConfiguration = apps.get_model( # pylint: disable=invalid-name 'sap_success_factors', 'SAPSuccessFactorsEnterpriseCustomerConfiguration' ) oauth_access_token, _ = SAPSuccessFactorsAPIClient.get_oauth_access_token( self.enterprise_configuration.sapsf_base_url, self.enterprise_configuration.key, self.enterprise_configuration.secret,
python
{ "resource": "" }
q256831
SAPSuccessFactorsAPIClient._call_post_with_session
validation
def _call_post_with_session(self, url, payload): """ Make a post request using the session object to a SuccessFactors endpoint. Args: url (str): The url to post to. payload (str): The json encoded payload to post. """ now = datetime.datetime.utcnow() if now >=
python
{ "resource": "" }
q256832
SAPSuccessFactorsAPIClient.get_inactive_sap_learners
validation
def get_inactive_sap_learners(self): """ Make a GET request using the session object to a SuccessFactors endpoint for inactive learners. Example: sap_search_student_url: "/learning/odatav4/searchStudent/v1/Students? $filter=criteria/isActive eq False&$select=studentID" SAP API response: { u'@odata.metadataEtag': u'W/"17090d86-20fa-49c8-8de0-de1d308c8b55"', u'value': [ { u'studentID': u'admint6', }, { u'studentID': u'adminsap1', } ] } Returns: List of inactive learners [ { u'studentID': u'admint6' }, { u'studentID': u'adminsap1' } ] """ now = datetime.datetime.utcnow()
python
{ "resource": "" }
q256833
SAPSuccessFactorsAPIClient._call_search_students_recursively
validation
def _call_search_students_recursively(self, sap_search_student_url, all_inactive_learners, page_size, start_at): """ Make recursive GET calls to traverse the paginated API response for search students. """ search_student_paginated_url = '{sap_search_student_url}&{pagination_criterion}'.format( sap_search_student_url=sap_search_student_url, pagination_criterion='$count=true&$top={page_size}&$skip={start_at}'.format( page_size=page_size, start_at=start_at, ), ) try: response = self.session.get(search_student_paginated_url) sap_inactive_learners = response.json() except (ConnectionError, Timeout): LOGGER.warning( 'Unable to fetch inactive learners from SAP searchStudent API with url ' '"{%s}".', search_student_paginated_url, ) return None if 'error' in sap_inactive_learners: LOGGER.warning( 'SAP searchStudent API for customer %s and base url %s returned response with ' 'error message
python
{ "resource": "" }
q256834
UserFilterBackend.filter_queryset
validation
def filter_queryset(self, request, queryset, view): """ Filter only for the user's ID if non-staff. """ if not request.user.is_staff:
python
{ "resource": "" }
q256835
EnterpriseCustomerUserFilterBackend.filter_queryset
validation
def filter_queryset(self, request, queryset, view): """ Apply incoming filters only if user is staff. If not, only filter by user's ID. """ if request.user.is_staff: email = request.query_params.get('email', None) username = request.query_params.get('username', None) query_parameters = {} if email: query_parameters.update(email=email) if username:
python
{ "resource": "" }
q256836
LearnerTransmitter.transmit
validation
def transmit(self, payload, **kwargs): """ Send a completion status call to the integrated channel using the client. Args: payload: The learner completion data payload to send to the integrated channel. kwargs: Contains integrated channel-specific information for customized transmission variables. - app_label: The app label of the integrated channel for whom to store learner data records for. - model_name: The name of the specific learner data record model to use. - remote_user_id: The remote ID field name of the learner on the audit model. """ IntegratedChannelLearnerDataTransmissionAudit = apps.get_model( # pylint: disable=invalid-name app_label=kwargs.get('app_label', 'integrated_channel'), model_name=kwargs.get('model_name', 'LearnerDataTransmissionAudit'), ) # Since we have started sending courses to integrated channels instead of course runs, # we need to attempt to send transmissions with course keys and course run ids in order to # ensure that we account for whether courses or course runs exist in the integrated channel. # The exporters have been changed to return multiple transmission records to attempt, # one by course key and one by course run id. # If the transmission with the course key succeeds, the next one will get skipped.
python
{ "resource": "" }
q256837
LearnerTransmitter.handle_transmission_error
validation
def handle_transmission_error(self, learner_data, request_exception): """Handle the case where the transmission fails.""" try: sys_msg = request_exception.response.content except AttributeError: sys_msg = 'Not available' LOGGER.error( ( 'Failed to send completion status call for enterprise enrollment %s' 'with payload %s'
python
{ "resource": "" }
q256838
add_missing_price_information_message
validation
def add_missing_price_information_message(request, item): """ Add a message to the Django messages store indicating that we failed to retrieve price information about an item. :param request: The current request. :param item: The item for which price information is missing. Example: a program title, or a course. """ messages.warning( request, _( '{strong_start}We could not gather price information for {em_start}{item}{em_end}.{strong_end} ' '{span_start}If you continue to have these issues, please contact ' '{link_start}{platform_name} support{link_end}.{span_end}' ).format( item=item, em_start='<em>',
python
{ "resource": "" }
q256839
validate_image_extension
validation
def validate_image_extension(value): """ Validate that a particular image extension. """ config = get_app_config()
python
{ "resource": "" }
q256840
validate_image_size
validation
def validate_image_size(image): """ Validate that a particular image size. """ config = get_app_config() valid_max_image_size_in_bytes = config.valid_max_image_size * 1024 if config and not image.size <= valid_max_image_size_in_bytes:
python
{ "resource": "" }
q256841
get_enterprise_customer_from_catalog_id
validation
def get_enterprise_customer_from_catalog_id(catalog_id): """ Get the enterprise customer id given an enterprise customer catalog id. """ try:
python
{ "resource": "" }
q256842
on_init
validation
def on_init(app): # pylint: disable=unused-argument """ Run sphinx-apidoc after Sphinx initialization. Read the Docs won't run tox or custom shell commands, so we need this to avoid checking in the generated reStructuredText files. """ docs_path = os.path.abspath(os.path.dirname(__file__)) root_path = os.path.abspath(os.path.join(docs_path, '..')) apidoc_path = 'sphinx-apidoc' if hasattr(sys, 'real_prefix'): # Check to see if we are in a virtualenv
python
{ "resource": "" }
q256843
IntegratedChannelCommandMixin.get_integrated_channels
validation
def get_integrated_channels(self, options): """ Generates a list of active integrated channels for active customers, filtered from the given options. Raises errors when invalid options are encountered. See ``add_arguments`` for the accepted options. """ channel_classes = self.get_channel_classes(options.get('channel'))
python
{ "resource": "" }
q256844
IntegratedChannelCommandMixin.get_enterprise_customer
validation
def get_enterprise_customer(uuid): """ Returns the enterprise customer requested for the given uuid, None if not. Raises CommandError if uuid is invalid. """ if uuid is None: return None try:
python
{ "resource": "" }
q256845
IntegratedChannelCommandMixin.get_channel_classes
validation
def get_channel_classes(channel_code): """ Assemble a list of integrated channel classes to transmit to. If a valid channel type was provided, use it. Otherwise, use all the available channel types. """ if channel_code: # Channel code is case-insensitive channel_code = channel_code.upper() if channel_code not in INTEGRATED_CHANNEL_CHOICES:
python
{ "resource": "" }
q256846
LearnerCourseCompletionStatement.get_result
validation
def get_result(self, course_grade): """ Get result for the statement. Arguments: course_grade (CourseGrade): Course grade. """ return Result(
python
{ "resource": "" }
q256847
get_requirements
validation
def get_requirements(requirements_file): """ Get the contents of a file listing the requirements """ lines = open(requirements_file).readlines() dependencies = [] dependency_links = [] for line in lines: package = line.strip() if package.startswith('#'): # Skip pure comment lines continue if any(package.startswith(prefix) for prefix in VCS_PREFIXES): # VCS reference for dev purposes, expect a trailing comment # with the normal requirement package_link, __, package = package.rpartition('#') # Remove -e <version_control> string
python
{ "resource": "" }
q256848
EnterpriseCustomerPluginConfiguration.transmit_learner_data
validation
def transmit_learner_data(self, user): """ Iterate over each learner data record and transmit it to the integrated channel. """
python
{ "resource": "" }
q256849
EnterpriseCustomerPluginConfiguration.transmit_content_metadata
validation
def transmit_content_metadata(self, user): """ Transmit content metadata to integrated channel. """ exporter = self.get_content_metadata_exporter(user)
python
{ "resource": "" }
q256850
DegreedLearnerExporter.get_learner_data_records
validation
def get_learner_data_records( self, enterprise_enrollment, completed_date=None, is_passing=False, **kwargs ): # pylint: disable=arguments-differ,unused-argument """ Return a DegreedLearnerDataTransmissionAudit with the given enrollment and course completion data. If completed_date is None, then course completion has not been met. If no remote ID can be found, return None. """ # Degreed expects completion dates of the form 'yyyy-mm-dd'. completed_timestamp = completed_date.strftime("%F") if isinstance(completed_date, datetime) else None if enterprise_enrollment.enterprise_customer_user.get_remote_id() is not None: DegreedLearnerDataTransmissionAudit = apps.get_model( # pylint: disable=invalid-name 'degreed', 'DegreedLearnerDataTransmissionAudit' ) # We return two records here, one with the course key and one with the course run id, to account for # uncertainty about the type of content (course vs. course run) that was sent to the integrated channel. return [ DegreedLearnerDataTransmissionAudit( enterprise_course_enrollment_id=enterprise_enrollment.id, degreed_user_email=enterprise_enrollment.enterprise_customer_user.user_email,
python
{ "resource": "" }
q256851
TemplatePreviewView.get
validation
def get(self, request, template_id, view_type): """ Render the given template with the stock data. """ template = get_object_or_404(EnrollmentNotificationEmailTemplate, pk=template_id) if view_type not in self.view_type_contexts: return HttpResponse(status=404) base_context = self.view_type_contexts[view_type].copy()
python
{ "resource": "" }
q256852
EnterpriseCustomerTransmitCoursesView._build_admin_context
validation
def _build_admin_context(request, customer): """ Build common admin context. """ opts = customer._meta codename = get_permission_codename('change', opts)
python
{ "resource": "" }
q256853
EnterpriseCustomerTransmitCoursesView.get
validation
def get(self, request, enterprise_customer_uuid): """ Handle GET request - render "Transmit courses metadata" form. Arguments: request (django.http.request.HttpRequest): Request instance enterprise_customer_uuid (str): Enterprise Customer UUID Returns: django.http.response.HttpResponse: HttpResponse """
python
{ "resource": "" }
q256854
EnterpriseCustomerManageLearnersView.get_enterprise_customer_user_queryset
validation
def get_enterprise_customer_user_queryset(self, request, search_keyword, customer_uuid, page_size=PAGE_SIZE): """ Get the list of EnterpriseCustomerUsers we want to render. Arguments: request (HttpRequest): HTTP Request instance. search_keyword (str): The keyword to search for in users' email addresses and usernames. customer_uuid (str): A unique identifier to filter down to only users linked to a particular EnterpriseCustomer. page_size (int): Number of learners displayed in each paginated set. """ page = request.GET.get('page', 1) learners = EnterpriseCustomerUser.objects.filter(enterprise_customer__uuid=customer_uuid) user_ids = learners.values_list('user_id', flat=True)
python
{ "resource": "" }
q256855
EnterpriseCustomerManageLearnersView.get_pending_users_queryset
validation
def get_pending_users_queryset(self, search_keyword, customer_uuid): """ Get the list of PendingEnterpriseCustomerUsers we want to render. Args: search_keyword (str): The keyword to search for in pending users' email addresses. customer_uuid (str): A unique identifier to filter down to only pending users linked to a particular EnterpriseCustomer.
python
{ "resource": "" }
q256856
EnterpriseCustomerManageLearnersView._handle_singular
validation
def _handle_singular(cls, enterprise_customer, manage_learners_form): """ Link single user by email or username. Arguments: enterprise_customer (EnterpriseCustomer): learners will be linked to this Enterprise Customer instance manage_learners_form (ManageLearnersForm): bound ManageLearners form instance """ form_field_value = manage_learners_form.cleaned_data[ManageLearnersForm.Fields.EMAIL_OR_USERNAME] email = email_or_username__to__email(form_field_value) try:
python
{ "resource": "" }
q256857
EnterpriseCustomerManageLearnersView._handle_bulk_upload
validation
def _handle_bulk_upload(cls, enterprise_customer, manage_learners_form, request, email_list=None): """ Bulk link users by email. Arguments: enterprise_customer (EnterpriseCustomer): learners will be linked to this Enterprise Customer instance manage_learners_form (ManageLearnersForm): bound ManageLearners form instance request (django.http.request.HttpRequest): HTTP Request instance email_list (iterable): A list of pre-processed email addresses to handle using the form """ errors = [] emails = set() already_linked_emails = [] duplicate_emails = [] csv_file = manage_learners_form.cleaned_data[ManageLearnersForm.Fields.BULK_UPLOAD] if email_list: parsed_csv = [{ManageLearnersForm.CsvColumns.EMAIL: email} for email in email_list] else: parsed_csv = parse_csv(csv_file, expected_columns={ManageLearnersForm.CsvColumns.EMAIL}) try: for index, row in enumerate(parsed_csv): email = row[ManageLearnersForm.CsvColumns.EMAIL] try: already_linked = validate_email_to_link(email, ignore_existing=True) except ValidationError as exc: message = _("Error at line {line}: {message}\n").format(line=index + 1, message=exc) errors.append(message) else: if already_linked: already_linked_emails.append((email, already_linked.enterprise_customer)) elif email in emails: duplicate_emails.append(email) else: emails.add(email) except ValidationError as exc: errors.append(exc) if errors: manage_learners_form.add_error( ManageLearnersForm.Fields.GENERAL_ERRORS, ValidationMessages.BULK_LINK_FAILED ) for error in errors: manage_learners_form.add_error(ManageLearnersForm.Fields.BULK_UPLOAD, error) return # There were no errors. Now do the actual linking: for email in emails: EnterpriseCustomerUser.objects.link_user(enterprise_customer, email) # Report what happened: count = len(emails) messages.success(request, ungettext( "{count} new learner was added to {enterprise_customer_name}.", "{count} new learners were added to {enterprise_customer_name}.", count ).format(count=count, enterprise_customer_name=enterprise_customer.name)) this_customer_linked_emails = [ email for email, customer in already_linked_emails if customer == enterprise_customer ]
python
{ "resource": "" }
q256858
EnterpriseCustomerManageLearnersView.enroll_user
validation
def enroll_user(cls, enterprise_customer, user, course_mode, *course_ids): """ Enroll a single user in any number of courses using a particular course mode. Args: enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment user: The user who needs to be enrolled in the course course_mode: The mode with which the enrollment should be created *course_ids: An iterable containing any number of course IDs to eventually enroll the user in. Returns: Boolean: Whether or not enrollment succeeded for all courses specified """ enterprise_customer_user, __ = EnterpriseCustomerUser.objects.get_or_create( enterprise_customer=enterprise_customer, user_id=user.id ) enrollment_client = EnrollmentApiClient() succeeded = True for course_id in course_ids: try: enrollment_client.enroll_user_in_course(user.username, course_id, course_mode) except HttpClientError as exc: # Check if user is already enrolled then we should ignore exception if cls.is_user_enrolled(user, course_id, course_mode): succeeded = True
python
{ "resource": "" }
q256859
EnterpriseCustomerManageLearnersView.is_user_enrolled
validation
def is_user_enrolled(cls, user, course_id, course_mode): """ Query the enrollment API and determine if a learner is enrolled in a given course run track. Args: user: The user whose enrollment needs to be checked course_mode: The mode with which the enrollment should be checked course_id: course id of the course where enrollment should be checked. Returns: Boolean: Whether or not enrollment exists """ enrollment_client = EnrollmentApiClient() try: enrollments = enrollment_client.get_course_enrollment(user.username, course_id) if enrollments and course_mode == enrollments.get('mode'):
python
{ "resource": "" }
q256860
EnterpriseCustomerManageLearnersView.get_users_by_email
validation
def get_users_by_email(cls, emails): """ Accept a list of emails, and separate them into users that exist on OpenEdX and users who don't. Args: emails: An iterable of email addresses to split between existing and nonexisting Returns: users: Queryset of users who exist in the OpenEdX platform and who were in the list of email addresses missing_emails: List of unique emails which
python
{ "resource": "" }
q256861
EnterpriseCustomerManageLearnersView.enroll_users_in_program
validation
def enroll_users_in_program(cls, enterprise_customer, program_details, course_mode, emails, cohort=None): """ Enroll existing users in all courses in a program, and create pending enrollments for nonexisting users. Args: enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment program_details: The details of the program in which we're enrolling course_mode (str): The mode with which we're enrolling in the program emails: An iterable of email addresses which need to be enrolled Returns: successes: A list of users who were successfully enrolled in all courses of the program pending: A list of PendingEnterpriseCustomerUsers who were successfully linked and had pending enrollments created for them in the database failures: A list of users who could not be enrolled in the program """ existing_users, unregistered_emails = cls.get_users_by_email(emails) course_ids = get_course_runs_from_program(program_details) successes = [] pending = [] failures = [] for user in existing_users:
python
{ "resource": "" }
q256862
EnterpriseCustomerManageLearnersView.enroll_users_in_course
validation
def enroll_users_in_course(cls, enterprise_customer, course_id, course_mode, emails): """ Enroll existing users in a course, and create a pending enrollment for nonexisting users. Args: enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment course_id (str): The unique identifier of the course in which we're enrolling course_mode (str): The mode with which we're enrolling in the course emails: An iterable of email addresses which need to be enrolled Returns: successes: A list of users who were successfully enrolled in the course pending: A list of PendingEnterpriseCustomerUsers who were successfully linked and had pending enrollments created for them in the database failures: A list of users who could not be enrolled in the course """ existing_users, unregistered_emails = cls.get_users_by_email(emails) successes = [] pending = [] failures = [] for user in existing_users:
python
{ "resource": "" }
q256863
EnterpriseCustomerManageLearnersView.send_messages
validation
def send_messages(cls, http_request, message_requests): """ Deduplicate any outgoing message requests, and send the remainder. Args: http_request: The HTTP request in whose response we want to embed the messages message_requests: A list of undeduplicated messages in the form of tuples of message type and text- for example, ('error', 'Something
python
{ "resource": "" }
q256864
EnterpriseCustomerManageLearnersView.notify_program_learners
validation
def notify_program_learners(cls, enterprise_customer, program_details, users): """ Notify learners about a program in which they've been enrolled. Args: enterprise_customer: The EnterpriseCustomer being linked to program_details: Details about the specific program the learners were enrolled in users: An iterable of the users or pending users who were enrolled """ program_name = program_details.get('title') program_branding = program_details.get('type') program_uuid = program_details.get('uuid') lms_root_url = get_configuration_value_for_site( enterprise_customer.site, 'LMS_ROOT_URL', settings.LMS_ROOT_URL ) program_path = urlquote( '/dashboard/programs/{program_uuid}/?tpa_hint={tpa_hint}'.format( program_uuid=program_uuid, tpa_hint=enterprise_customer.identity_provider, ) ) destination_url = '{site}/{login_or_register}?next={program_path}'.format( site=lms_root_url, login_or_register='{login_or_register}', program_path=program_path ) program_type = 'program' program_start = get_earliest_start_date_from_program(program_details)
python
{ "resource": "" }
q256865
EnterpriseCustomerManageLearnersView.get_failed_enrollment_message
validation
def get_failed_enrollment_message(cls, users, enrolled_in): """ Create message for the users who were not able to be enrolled in a course or program. Args: users: An iterable of users who were not successfully enrolled enrolled_in (str): A string identifier for the course or program with which enrollment was attempted Returns: tuple: A 2-tuple containing a message type and message text """ failed_emails = [user.email for user in users] return (
python
{ "resource": "" }
q256866
EnterpriseCustomerManageLearnersView._enroll_users
validation
def _enroll_users( cls, request, enterprise_customer, emails, mode, course_id=None, program_details=None, notify=True ): """ Enroll the users with the given email addresses to the courses specified, either specifically or by program. Args: cls (type): The EnterpriseCustomerManageLearnersView class itself request: The HTTP request the enrollment is being created by enterprise_customer: The instance of EnterpriseCustomer whose attached users we're enrolling emails: An iterable of strings containing email addresses to enroll in a course mode: The enrollment mode the users will be enrolled in the course with course_id: The ID of the course in which we want to enroll program_details: Details about a program in which we want to enroll notify: Whether to notify (by email) the users that have been enrolled """ pending_messages = [] if course_id: succeeded, pending, failed = cls.enroll_users_in_course( enterprise_customer=enterprise_customer, course_id=course_id, course_mode=mode, emails=emails, ) all_successes = succeeded + pending if notify: enterprise_customer.notify_enrolled_learners( catalog_api_user=request.user, course_id=course_id, users=all_successes, ) if succeeded: pending_messages.append(cls.get_success_enrollment_message(succeeded, course_id)) if failed: pending_messages.append(cls.get_failed_enrollment_message(failed, course_id)) if pending: pending_messages.append(cls.get_pending_enrollment_message(pending, course_id)) if program_details:
python
{ "resource": "" }
q256867
EnterpriseCustomerManageLearnersView.get
validation
def get(self, request, customer_uuid): """ Handle GET request - render linked learners list and "Link learner" form. Arguments: request (django.http.request.HttpRequest): Request instance customer_uuid (str): Enterprise Customer UUID Returns:
python
{ "resource": "" }
q256868
EnterpriseCustomerManageLearnersView.delete
validation
def delete(self, request, customer_uuid): """ Handle DELETE request - handle unlinking learner. Arguments: request (django.http.request.HttpRequest): Request instance customer_uuid (str): Enterprise Customer UUID Returns: django.http.response.HttpResponse: HttpResponse """ # TODO: pylint acts stupid - find a way around it without suppressing enterprise_customer = EnterpriseCustomer.objects.get(uuid=customer_uuid) # pylint: disable=no-member email_to_unlink = request.GET["unlink_email"] try: EnterpriseCustomerUser.objects.unlink_user( enterprise_customer=enterprise_customer, user_email=email_to_unlink )
python
{ "resource": "" }
q256869
DataSharingConsentQuerySet.proxied_get
validation
def proxied_get(self, *args, **kwargs): """ Perform the query and returns a single object matching the given keyword arguments. This customizes the queryset to return an instance of ``ProxyDataSharingConsent`` when the searched-for ``DataSharingConsent`` instance does not exist. """ original_kwargs = kwargs.copy() if 'course_id' in kwargs: try: # Check if we have a course ID or a course run ID course_run_key = str(CourseKey.from_string(kwargs['course_id'])) except InvalidKeyError: # The ID we have is for a course instead of a course run; fall through # to the second check. pass else: try: # Try to get the record for the course run specifically
python
{ "resource": "" }
q256870
ProxyDataSharingConsent.from_children
validation
def from_children(cls, program_uuid, *children): """ Build a ProxyDataSharingConsent using the details of the received consent records. """ if not children or any(child is None for child in children): return None granted = all((child.granted for child in children)) exists = any((child.exists for child in children)) usernames = set([child.username for child in children]) enterprises = set([child.enterprise_customer for child in children]) if not len(usernames) == len(enterprises) == 1: raise InvalidProxyConsent( 'Children used to create a bulk proxy consent object must '
python
{ "resource": "" }
q256871
ProxyDataSharingConsent.commit
validation
def commit(self): """ Commit a real ``DataSharingConsent`` object to the database, mirroring current field settings. :return: A ``DataSharingConsent`` object if validation is successful, otherwise ``None``. """ if self._child_consents: consents = [] for consent in self._child_consents: consent.granted = self.granted consents.append(consent.save() or consent) return ProxyDataSharingConsent.from_children(self.program_uuid, *consents) consent, _ = DataSharingConsent.objects.update_or_create(
python
{ "resource": "" }
q256872
Command.get_course_completions
validation
def get_course_completions(self, enterprise_customer, days): """ Get course completions via PersistentCourseGrade for all the learners of given enterprise customer. Arguments: enterprise_customer (EnterpriseCustomer): Include Course enrollments for learners of this enterprise customer.
python
{ "resource": "" }
q256873
Command.prefetch_users
validation
def prefetch_users(persistent_course_grades): """ Prefetch Users from the list of user_ids present in the persistent_course_grades. Arguments: persistent_course_grades (list): A list of PersistentCourseGrade. Returns: (dict): A dictionary containing user_id to user mapping.
python
{ "resource": "" }
q256874
get_identity_provider
validation
def get_identity_provider(provider_id): """ Get Identity Provider with given id. Return: Instance of ProviderConfig or None. """ try: from third_party_auth.provider import Registry # pylint: disable=redefined-outer-name except ImportError as exception: LOGGER.warning("Could not
python
{ "resource": "" }
q256875
get_idp_choices
validation
def get_idp_choices(): """ Get a list of identity providers choices for enterprise customer. Return: A list of choices of all identity providers, None if it can not get any available identity provider. """ try: from third_party_auth.provider import Registry # pylint: disable=redefined-outer-name except ImportError as exception: LOGGER.warning("Could not import Registry from third_party_auth.provider")
python
{ "resource": "" }
q256876
get_catalog_admin_url_template
validation
def get_catalog_admin_url_template(mode='change'): """ Get template of catalog admin url. URL template will contain a placeholder '{catalog_id}' for catalog id. Arguments: mode e.g. change/add. Returns: A string containing template for catalog url. Example: >>> get_catalog_admin_url_template('change') "http://localhost:18381/admin/catalogs/catalog/{catalog_id}/change/" """ api_base_url = getattr(settings, "COURSE_CATALOG_API_URL", "") # Extract FQDN (Fully Qualified Domain Name) from API URL. match =
python
{ "resource": "" }
q256877
build_notification_message
validation
def build_notification_message(template_context, template_configuration=None): """ Create HTML and plaintext message bodies for a notification. We receive a context with data we can use to render, as well as an optional site template configration - if we don't get a template configuration, we'll use the standard, built-in template. Arguments: template_context (dict): A set of data to render template_configuration: A database-backed object with templates stored that can be used to render a notification. """ if ( template_configuration is not None and template_configuration.html_template and
python
{ "resource": "" }
q256878
get_notification_subject_line
validation
def get_notification_subject_line(course_name, template_configuration=None): """ Get a subject line for a notification email. The method is designed to fail in a "smart" way; if we can't render a database-backed subject line template, then we'll fall back to a template saved in the Django settings; if we can't render _that_ one, then we'll fall through to a friendly string written into the code. One example of a failure case in which we want to fall back to a stock template would be if a site admin entered a subject line string that contained a template tag that wasn't available, causing a KeyError to be raised. Arguments: course_name (str): Course name to be rendered into the string template_configuration: A database-backed object with a stored subject line template """ stock_subject_template = _('You\'ve been enrolled in {course_name}!') default_subject_template = getattr(
python
{ "resource": "" }
q256879
send_email_notification_message
validation
def send_email_notification_message(user, enrolled_in, enterprise_customer, email_connection=None): """ Send an email notifying a user about their enrollment in a course. Arguments: user: Either a User object or a PendingEnterpriseCustomerUser that we can use to get details for the email enrolled_in (dict): The dictionary contains details of the enrollable object (either course or program) that the user enrolled in. This MUST contain a `name` key, and MAY contain the other following keys: - url: A human-friendly link to the enrollable's home page - type: Either `course` or `program` at present - branding: A special name for what the enrollable "is"; for example, "MicroMasters" would be the branding for a "MicroMasters Program" - start: A datetime object indicating when the enrollable will be available. enterprise_customer: The EnterpriseCustomer that the enrollment was created using. email_connection: An existing Django email connection that can be used without creating a new connection for each individual message """ if hasattr(user, 'first_name') and hasattr(user, 'username'): # PendingEnterpriseCustomerUsers don't have usernames or real names. We should # template slightly differently to make sure weird stuff doesn't happen. user_name = user.first_name if not user_name: user_name = user.username else: user_name = None # Users have an `email` attribute; PendingEnterpriseCustomerUsers have `user_email`.
python
{ "resource": "" }
q256880
get_enterprise_customer
validation
def get_enterprise_customer(uuid): """ Get the ``EnterpriseCustomer`` instance associated with ``uuid``. :param uuid: The universally unique ID of the enterprise customer. :return: The ``EnterpriseCustomer`` instance, or ``None`` if it doesn't exist. """ EnterpriseCustomer =
python
{ "resource": "" }
q256881
get_enterprise_customer_for_user
validation
def get_enterprise_customer_for_user(auth_user): """ Return enterprise customer instance for given user. Some users are associated with an enterprise customer via `EnterpriseCustomerUser` model, 1. if given user is associated with any enterprise customer, return enterprise customer. 2. otherwise return `None`. Arguments: auth_user (contrib.auth.User): Django User Returns: (EnterpriseCustomer): enterprise customer
python
{ "resource": "" }
q256882
get_enterprise_customer_user
validation
def get_enterprise_customer_user(user_id, enterprise_uuid): """ Return the object for EnterpriseCustomerUser. Arguments: user_id (str): user identifier enterprise_uuid (UUID): Universally unique identifier for the enterprise customer. Returns: (EnterpriseCustomerUser): enterprise customer user record """ EnterpriseCustomerUser = apps.get_model('enterprise', 'EnterpriseCustomerUser') # pylint: disable=invalid-name try: return
python
{ "resource": "" }
q256883
get_course_track_selection_url
validation
def get_course_track_selection_url(course_run, query_parameters): """ Return track selection url for the given course. Arguments: course_run (dict): A dictionary containing course run metadata. query_parameters (dict): A dictionary containing query parameters to be added to course selection url. Raises: (KeyError): Raised when course run dict does not have 'key' key. Returns: (str): Course track selection url. """ try: course_root = reverse('course_modes_choose', kwargs={'course_id': course_run['key']}) except KeyError: LOGGER.exception(
python
{ "resource": "" }
q256884
update_query_parameters
validation
def update_query_parameters(url, query_parameters): """ Return url with updated query parameters. Arguments: url (str): Original url whose query parameters need to be updated. query_parameters (dict): A dictionary containing query parameters to be added to course selection url. Returns: (slug): slug identifier for the identity provider that can be used for identity verification of users associated the
python
{ "resource": "" }
q256885
filter_audit_course_modes
validation
def filter_audit_course_modes(enterprise_customer, course_modes): """ Filter audit course modes out if the enterprise customer has not enabled the 'Enable audit enrollment' flag. Arguments: enterprise_customer: The EnterpriseCustomer that the enrollment was
python
{ "resource": "" }
q256886
get_enterprise_customer_or_404
validation
def get_enterprise_customer_or_404(enterprise_uuid): """ Given an EnterpriseCustomer UUID, return the corresponding EnterpriseCustomer or raise a 404. Arguments: enterprise_uuid (str): The UUID (in string form) of the EnterpriseCustomer to fetch. Returns: (EnterpriseCustomer): The EnterpriseCustomer given the UUID. """ EnterpriseCustomer = apps.get_model('enterprise', 'EnterpriseCustomer') # pylint: disable=invalid-name try: enterprise_uuid =
python
{ "resource": "" }
q256887
get_cache_key
validation
def get_cache_key(**kwargs): """ Get MD5 encoded cache key for given arguments. Here is the format of key before MD5 encryption. key1:value1__key2:value2 ... Example: >>> get_cache_key(site_domain="example.com", resource="enterprise") # Here is key format for above call # "site_domain:example.com__resource:enterprise" a54349175618ff1659dee0978e3149ca Arguments:
python
{ "resource": "" }
q256888
traverse_pagination
validation
def traverse_pagination(response, endpoint): """ Traverse a paginated API response. Extracts and concatenates "results" (list of dict) returned by DRF-powered APIs. Arguments: response (Dict): Current response dict from service API endpoint (slumber Resource object): slumber Resource object from edx-rest-api-client Returns: list of dict. """ results = response.get('results',
python
{ "resource": "" }
q256889
ungettext_min_max
validation
def ungettext_min_max(singular, plural, range_text, min_val, max_val): """ Return grammatically correct, translated text based off of a minimum and maximum value. Example: min = 1, max = 1, singular = '{} hour required for this course', plural = '{} hours required for this course' output = '1 hour required for this course' min = 2, max = 2, singular = '{} hour required for this course', plural = '{} hours required for this course' output = '2 hours required for this course' min = 2, max = 4, range_text = '{}-{} hours required for this course' output = '2-4 hours required for this course' min = None, max = 2, plural = '{} hours required for this course' output = '2 hours required for this course' Expects ``range_text`` to already have a translation function called on it. Returns:
python
{ "resource": "" }
q256890
format_price
validation
def format_price(price, currency='$'): """ Format the price to have the appropriate currency and digits.. :param price: The price amount. :param currency: The currency for the price. :return: A formatted price string, i.e. '$10', '$10.52'.
python
{ "resource": "" }
q256891
get_configuration_value_for_site
validation
def get_configuration_value_for_site(site, key, default=None): """ Get the site configuration value for a key, unless a site configuration does not exist for that site. Useful for testing when no Site Configuration exists in edx-enterprise or if a site in LMS doesn't have a configuration tied to it. :param site: A Site model object :param key: The name of the value to retrieve
python
{ "resource": "" }
q256892
get_configuration_value
validation
def get_configuration_value(val_name, default=None, **kwargs): """ Get a configuration value, or fall back to ``default`` if it doesn't exist. Also takes a `type` argument to guide which particular upstream method to use when trying to retrieve a value. Current types include: - `url` to specifically get a URL. """
python
{ "resource": "" }
q256893
get_request_value
validation
def get_request_value(request, key, default=None): """ Get the value in the request, either through query parameters or posted data, from a key. :param request: The request from which the value should be gotten. :param key: The key to use to get the desired value. :param default: The backup value to use in case the input key cannot help us get the value. :return: The value
python
{ "resource": "" }
q256894
track_enrollment
validation
def track_enrollment(pathway, user_id, course_run_id, url_path=None): """ Emit a track event for enterprise course enrollment. """ track_event(user_id, 'edx.bi.user.enterprise.onboarding', {
python
{ "resource": "" }
q256895
is_course_run_enrollable
validation
def is_course_run_enrollable(course_run): """ Return true if the course run is enrollable, false otherwise. We look for the following criteria: - end is greater than now OR null - enrollment_start is less than now OR null - enrollment_end is greater than now OR null """ now = datetime.datetime.now(pytz.UTC) end = parse_datetime_handle_invalid(course_run.get('end'))
python
{ "resource": "" }
q256896
is_course_run_upgradeable
validation
def is_course_run_upgradeable(course_run): """ Return true if the course run has a verified seat with an unexpired upgrade deadline, false otherwise. """ now = datetime.datetime.now(pytz.UTC)
python
{ "resource": "" }
q256897
get_closest_course_run
validation
def get_closest_course_run(course_runs): """ Return course run with start date closest to now. """ if len(course_runs) == 1: return course_runs[0] now = datetime.datetime.now(pytz.UTC) # course runs with no start
python
{ "resource": "" }
q256898
get_current_course_run
validation
def get_current_course_run(course, users_active_course_runs): """ Return the current course run on the following conditions. - If user has active course runs (already enrolled) then return course run with closest start date Otherwise it will check the following logic: - Course run is enrollable (see is_course_run_enrollable) - Course run has a verified seat and the upgrade deadline has not expired. - Course run start date is closer to now than any other enrollable/upgradeable course runs. - If no enrollable/upgradeable course runs, return course run with most recent start date. """ current_course_run = None filtered_course_runs = [] all_course_runs = course['course_runs'] if users_active_course_runs: current_course_run = get_closest_course_run(users_active_course_runs) else: for course_run in all_course_runs:
python
{ "resource": "" }
q256899
strip_html_tags
validation
def strip_html_tags(text, allowed_tags=None): """ Strip all tags from a string except those tags provided in `allowed_tags` parameter. Args: text (str): string to strip html tags from allowed_tags (list): allowed list of html tags Returns: a string without html tags """ if text is None:
python
{ "resource": "" }