_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q256700
create_switch
validation
def create_switch(apps, schema_editor): """Create the `role_based_access_control` switch if it does not already exist.""" Switch = apps.get_model('waffle', 'Switch') Switch.objects.update_or_create(name=ENTERPRISE_ROLE_BASED_ACCESS_CONTROL_SWITCH, defaults={'active': False})
python
{ "resource": "" }
q256701
delete_switch
validation
def delete_switch(apps, schema_editor): """Delete the `role_based_access_control` switch.""" Switch = apps.get_model('waffle', 'Switch') Switch.objects.filter(name=ENTERPRISE_ROLE_BASED_ACCESS_CONTROL_SWITCH).delete()
python
{ "resource": "" }
q256702
create_switch
validation
def create_switch(apps, schema_editor): """Create and activate the SAP_USE_ENTERPRISE_ENROLLMENT_PAGE switch if it does not already exist.""" Switch = apps.get_model('waffle', 'Switch') Switch.objects.get_or_create(name='SAP_USE_ENTERPRISE_ENROLLMENT_PAGE', defaults={'active': False})
python
{ "resource": "" }
q256703
SapSuccessFactorsLearnerTransmitter.transmit
validation
def transmit(self, payload, **kwargs): """ Send a completion status call to SAP SuccessFactors using the client. Args: payload: The learner completion data payload to send to SAP SuccessFactors """ kwargs['app_label'] = 'sap_success_factors' kwargs['model_nam...
python
{ "resource": "" }
q256704
SapSuccessFactorsLearnerTransmitter.handle_transmission_error
validation
def handle_transmission_error(self, learner_data, request_exception): """Handle the case where the employee on SAPSF's side is marked as inactive.""" try: sys_msg = request_exception.response.content except AttributeError: pass else: if 'user account i...
python
{ "resource": "" }
q256705
ServiceUserThrottle.allow_request
validation
def allow_request(self, request, view): """ Modify throttling for service users. Updates throttling rate if the request is coming from the service user, and defaults to UserRateThrottle's configured setting otherwise. Updated throttling rate comes from `DEFAULT_THROTTLE_RATES` ...
python
{ "resource": "" }
q256706
ServiceUserThrottle.update_throttle_scope
validation
def update_throttle_scope(self): """ Update throttle scope so that service user throttle rates are applied. """ self.scope = SERVICE_USER_SCOPE self.rate = self.get_rate() self.num_requests, self.duration = self.parse_rate(self.rate)
python
{ "resource": "" }
q256707
EcommerceApiClient.get_course_final_price
validation
def get_course_final_price(self, mode, currency='$', enterprise_catalog_uuid=None): """ Get course mode's SKU discounted price after applying any entitlement available for this user. Returns: str: Discounted price of the course mode. """ try: price_detai...
python
{ "resource": "" }
q256708
EnterpriseCourseContextSerializerMixin.update_enterprise_courses
validation
def update_enterprise_courses(self, enterprise_customer, course_container_key='results', **kwargs): """ This method adds enterprise-specific metadata for each course. We are adding following field in all the courses. tpa_hint: a string for identifying Identity Provider. ...
python
{ "resource": "" }
q256709
EnterpriseCourseContextSerializerMixin.update_course
validation
def update_course(self, course, enterprise_customer, enterprise_context): """ Update course metadata of the given course and return updated course. Arguments: course (dict): Course Metadata returned by course catalog API enterprise_customer (EnterpriseCustomer): enterpri...
python
{ "resource": "" }
q256710
EnterpriseCourseContextSerializerMixin.update_course_runs
validation
def update_course_runs(self, course_runs, enterprise_customer, enterprise_context): """ Update Marketing urls in course metadata and return updated course. Arguments: course_runs (list): List of course runs. enterprise_customer (EnterpriseCustomer): enterprise customer i...
python
{ "resource": "" }
q256711
LearnerExporter.export
validation
def export(self): """ Collect learner data for the ``EnterpriseCustomer`` where data sharing consent is granted. Yields a learner data object for each enrollment, containing: * ``enterprise_enrollment``: ``EnterpriseCourseEnrollment`` object. * ``completed_date``: datetime inst...
python
{ "resource": "" }
q256712
LearnerExporter.get_learner_data_records
validation
def get_learner_data_records(self, enterprise_enrollment, completed_date=None, grade=None, is_passing=False): """ Generate a learner data transmission audit with fields properly filled in. """ # pylint: disable=invalid-name LearnerDataTransmissionAudit = apps.get_model('integrate...
python
{ "resource": "" }
q256713
LearnerExporter._collect_certificate_data
validation
def _collect_certificate_data(self, enterprise_enrollment): """ Collect the learner completion data from the course certificate. Used for Instructor-paced courses. If no certificate is found, then returns the completed_date = None, grade = In Progress, on the idea that a certif...
python
{ "resource": "" }
q256714
LearnerExporter._collect_grades_data
validation
def _collect_grades_data(self, enterprise_enrollment, course_details): """ Collect the learner completion data from the Grades API. Used for self-paced courses. Args: enterprise_enrollment (EnterpriseCourseEnrollment): the enterprise enrollment record for which we need to ...
python
{ "resource": "" }
q256715
LearnerInfoSerializer.get_enterprise_user_id
validation
def get_enterprise_user_id(self, obj): """ Get enterprise user id from user object. Arguments: obj (User): Django User object Returns: (int): Primary Key identifier for enterprise user object. """ # An enterprise learner can not belong to multipl...
python
{ "resource": "" }
q256716
LearnerInfoSerializer.get_enterprise_sso_uid
validation
def get_enterprise_sso_uid(self, obj): """ Get enterprise SSO UID. Arguments: obj (User): Django User object Returns: (str): string containing UUID for enterprise customer's Identity Provider. """ # An enterprise learner can not belong to multipl...
python
{ "resource": "" }
q256717
CourseInfoSerializer.get_course_duration
validation
def get_course_duration(self, obj): """ Get course's duration as a timedelta. Arguments: obj (CourseOverview): CourseOverview object Returns: (timedelta): Duration of a course. """ duration = obj.end - obj.start if obj.start and obj.end else None...
python
{ "resource": "" }
q256718
SapSuccessFactorsContentMetadataTransmitter._remove_failed_items
validation
def _remove_failed_items(self, failed_items, items_to_create, items_to_update, items_to_delete): """ Remove content metadata items from the `items_to_create`, `items_to_update`, `items_to_delete` dicts. Arguments: failed_items (list): Failed Items to be removed. items_to...
python
{ "resource": "" }
q256719
Command.parse_arguments
validation
def parse_arguments(*args, **options): # pylint: disable=unused-argument """ Parse and validate arguments for send_course_enrollments command. Arguments: *args: Positional arguments passed to the command **options: optional arguments passed to the command Retur...
python
{ "resource": "" }
q256720
Command.handle
validation
def handle(self, *args, **options): """ Send xAPI statements. """ if not CourseEnrollment: raise NotConnectedToOpenEdX("This package must be installed in an OpenEdX environment.") days, enterprise_customer = self.parse_arguments(*args, **options) if enterpri...
python
{ "resource": "" }
q256721
Command.get_course_enrollments
validation
def get_course_enrollments(self, enterprise_customer, days): """ Get course enrollments for all the learners of given enterprise customer. Arguments: enterprise_customer (EnterpriseCustomer): Include Course enrollments for learners of this enterprise customer. ...
python
{ "resource": "" }
q256722
course_modal
validation
def course_modal(context, course=None): """ Django template tag that returns course information to display in a modal. You may pass in a particular course if you like. Otherwise, the modal will look for course context within the parent context. Usage: {% course_modal %} {% course_m...
python
{ "resource": "" }
q256723
link_to_modal
validation
def link_to_modal(link_text, index, autoescape=True): # pylint: disable=unused-argument """ Django template filter that returns an anchor with attributes useful for course modal selection. General Usage: {{ link_text|link_to_modal:index }} Examples: {{ course_title|link_to_modal:forlo...
python
{ "resource": "" }
q256724
populate_data_sharing_consent
validation
def populate_data_sharing_consent(apps, schema_editor): """ Populates the ``DataSharingConsent`` model with the ``enterprise`` application's consent data. Consent data from the ``enterprise`` application come from the ``EnterpriseCourseEnrollment`` model. """ DataSharingConsent = apps.get_model('co...
python
{ "resource": "" }
q256725
DegreedAPIClient.create_course_completion
validation
def create_course_completion(self, user_id, payload): # pylint: disable=unused-argument """ Send a completion status payload to the Degreed Completion Status endpoint Args: user_id: Unused. payload: JSON encoded object (serialized from DegreedLearnerDataTransmissionAudi...
python
{ "resource": "" }
q256726
DegreedAPIClient.delete_course_completion
validation
def delete_course_completion(self, user_id, payload): # pylint: disable=unused-argument """ Delete a completion status previously sent to the Degreed Completion Status endpoint Args: user_id: Unused. payload: JSON encoded object (serialized from DegreedLearnerDataTransm...
python
{ "resource": "" }
q256727
DegreedAPIClient._sync_content_metadata
validation
def _sync_content_metadata(self, serialized_data, http_method): """ Synchronize content metadata using the Degreed course content API. Args: serialized_data: JSON-encoded object containing content metadata. http_method: The HTTP method to use for the API request. ...
python
{ "resource": "" }
q256728
DegreedAPIClient._post
validation
def _post(self, url, data, scope): """ Make a POST request using the session object to a Degreed endpoint. Args: url (str): The url to send a POST request to. data (str): The json encoded payload to POST. scope (str): Must be one of the scopes Degreed expects...
python
{ "resource": "" }
q256729
DegreedAPIClient._delete
validation
def _delete(self, url, data, scope): """ Make a DELETE request using the session object to a Degreed endpoint. Args: url (str): The url to send a DELETE request to. data (str): The json encoded payload to DELETE. scope (str): Must be one of the scopes Degreed...
python
{ "resource": "" }
q256730
DegreedAPIClient._create_session
validation
def _create_session(self, scope): """ Instantiate a new session object for use in connecting with Degreed """ now = datetime.datetime.utcnow() if self.session is None or self.expires_at is None or now >= self.expires_at: # Create a new session with a valid token ...
python
{ "resource": "" }
q256731
EnterpriseViewSet.ensure_data_exists
validation
def ensure_data_exists(self, request, data, error_message=None): """ Ensure that the wrapped API client's response brings us valid data. If not, raise an error and log it. """ if not data: error_message = ( error_message or "Unable to fetch API response from e...
python
{ "resource": "" }
q256732
EnterpriseCustomerViewSet.contains_content_items
validation
def contains_content_items(self, request, pk, course_run_ids, program_uuids): """ Return whether or not the specified content is available to the EnterpriseCustomer. Multiple course_run_ids and/or program_uuids query parameters can be sent to this view to check for their existence in th...
python
{ "resource": "" }
q256733
EnterpriseCustomerViewSet.courses
validation
def courses(self, request, pk=None): # pylint: disable=invalid-name,unused-argument """ Retrieve the list of courses contained within the catalog linked to this enterprise. Only courses with active course runs are returned. A course run is considered active if it is currently open for ...
python
{ "resource": "" }
q256734
EnterpriseCustomerViewSet.course_enrollments
validation
def course_enrollments(self, request, pk): """ Creates a course enrollment for an EnterpriseCustomerUser. """ enterprise_customer = self.get_object() serializer = serializers.EnterpriseCustomerCourseEnrollmentsSerializer( data=request.data, many=True, ...
python
{ "resource": "" }
q256735
EnterpriseCustomerViewSet.with_access_to
validation
def with_access_to(self, request, *args, **kwargs): # pylint: disable=invalid-name,unused-argument """ Returns the list of enterprise customers the user has a specified group permission access to. """ self.queryset = self.queryset.order_by('name') enterprise_id = self.request.qu...
python
{ "resource": "" }
q256736
EnterpriseCustomerUserViewSet.entitlements
validation
def entitlements(self, request, pk=None): # pylint: disable=invalid-name,unused-argument """ Retrieve the list of entitlements available to this learner. Only those entitlements are returned that satisfy enterprise customer's data sharing setting. Arguments: request (HttpR...
python
{ "resource": "" }
q256737
EnterpriseCustomerCatalogViewSet.contains_content_items
validation
def contains_content_items(self, request, pk, course_run_ids, program_uuids): """ Return whether or not the EnterpriseCustomerCatalog contains the specified content. Multiple course_run_ids and/or program_uuids query parameters can be sent to this view to check for their existence in th...
python
{ "resource": "" }
q256738
EnterpriseCustomerCatalogViewSet.course_detail
validation
def course_detail(self, request, pk, course_key): # pylint: disable=invalid-name,unused-argument """ Return the metadata for the specified course. The course needs to be included in the specified EnterpriseCustomerCatalog in order for metadata to be returned from this endpoint. ...
python
{ "resource": "" }
q256739
EnterpriseCustomerCatalogViewSet.course_run_detail
validation
def course_run_detail(self, request, pk, course_id): # pylint: disable=invalid-name,unused-argument """ Return the metadata for the specified course run. The course run needs to be included in the specified EnterpriseCustomerCatalog in order for metadata to be returned from this endpoi...
python
{ "resource": "" }
q256740
EnterpriseCustomerCatalogViewSet.program_detail
validation
def program_detail(self, request, pk, program_uuid): # pylint: disable=invalid-name,unused-argument """ Return the metadata for the specified program. The program needs to be included in the specified EnterpriseCustomerCatalog in order for metadata to be returned from this endpoint. ...
python
{ "resource": "" }
q256741
EnterpriseCourseCatalogViewSet.list
validation
def list(self, request): """ DRF view to list all catalogs. Arguments: request (HttpRequest): Current request Returns: (Response): DRF response object containing course catalogs. """ catalog_api = CourseCatalogApiClient(request.user) cata...
python
{ "resource": "" }
q256742
EnterpriseCourseCatalogViewSet.retrieve
validation
def retrieve(self, request, pk=None): # pylint: disable=invalid-name """ DRF view to get catalog details. Arguments: request (HttpRequest): Current request pk (int): Course catalog identifier Returns: (Response): DRF response object containing cours...
python
{ "resource": "" }
q256743
EnterpriseCourseCatalogViewSet.courses
validation
def courses(self, request, enterprise_customer, pk=None): # pylint: disable=invalid-name """ Retrieve the list of courses contained within this catalog. Only courses with active course runs are returned. A course run is considered active if it is currently open for enrollment, or will ...
python
{ "resource": "" }
q256744
CouponCodesView.get_required_query_params
validation
def get_required_query_params(self, request): """ Gets ``email``, ``enterprise_name``, and ``number_of_codes``, which are the relevant parameters for this API endpoint. :param request: The request to this endpoint. :return: The ``email``, ``enterprise_name``, and ``number_of_cod...
python
{ "resource": "" }
q256745
CouponCodesView.get_missing_params_message
validation
def get_missing_params_message(self, parameter_state): """ Get a user-friendly message indicating a missing parameter for the API endpoint. """ params = ', '.join(name for name, present in parameter_state if not present) return self.MISSING_REQUIRED_PARAMS_MSG.format(params)
python
{ "resource": "" }
q256746
SapSuccessFactorsContentMetadataExporter.transform_title
validation
def transform_title(self, content_metadata_item): """ Return the title of the content item. """ title_with_locales = [] for locale in self.enterprise_configuration.get_locales(): title_with_locales.append({ 'locale': locale, 'value': c...
python
{ "resource": "" }
q256747
SapSuccessFactorsContentMetadataExporter.transform_description
validation
def transform_description(self, content_metadata_item): """ Return the description of the content item. """ description_with_locales = [] for locale in self.enterprise_configuration.get_locales(): description_with_locales.append({ 'locale': locale, ...
python
{ "resource": "" }
q256748
SapSuccessFactorsContentMetadataExporter.transform_image
validation
def transform_image(self, content_metadata_item): """ Return the image URI of the content item. """ image_url = '' if content_metadata_item['content_type'] in ['course', 'program']: image_url = content_metadata_item.get('card_image_url') elif content_metadata_...
python
{ "resource": "" }
q256749
SapSuccessFactorsContentMetadataExporter.transform_launch_points
validation
def transform_launch_points(self, content_metadata_item): """ Return the content metadata item launch points. SAPSF allows you to transmit an arry of content launch points which are meant to represent sections of a content item which a learner can launch into from SAPSF. Current...
python
{ "resource": "" }
q256750
SapSuccessFactorsContentMetadataExporter.transform_courserun_title
validation
def transform_courserun_title(self, content_metadata_item): """ Return the title of the courserun content item. """ title = content_metadata_item.get('title') or '' course_run_start = content_metadata_item.get('start') if course_run_start: if course_available...
python
{ "resource": "" }
q256751
SapSuccessFactorsContentMetadataExporter.transform_courserun_description
validation
def transform_courserun_description(self, content_metadata_item): """ Return the description of the courserun content item. """ description_with_locales = [] content_metadata_language_code = transform_language_code(content_metadata_item.get('content_language', '')) for lo...
python
{ "resource": "" }
q256752
SapSuccessFactorsContentMetadataExporter.transform_courserun_schedule
validation
def transform_courserun_schedule(self, content_metadata_item): """ Return the schedule of the courseun content item. """ start = content_metadata_item.get('start') or UNIX_MIN_DATE_STRING end = content_metadata_item.get('end') or UNIX_MAX_DATE_STRING return [{ ...
python
{ "resource": "" }
q256753
SapSuccessFactorsContentMetadataExporter.get_content_id
validation
def get_content_id(self, content_metadata_item): """ Return the id for the given content_metadata_item, `uuid` for programs or `key` for other content """ content_id = content_metadata_item.get('key', '') if content_metadata_item['content_type'] == 'program': content_...
python
{ "resource": "" }
q256754
parse_datetime_to_epoch
validation
def parse_datetime_to_epoch(datestamp, magnitude=1.0): """ Convert an ISO-8601 datetime string to a Unix epoch timestamp in some magnitude. By default, returns seconds. """ parsed_datetime = parse_lms_api_datetime(datestamp) time_since_epoch = parsed_datetime - UNIX_EPOCH return int(time_si...
python
{ "resource": "" }
q256755
chunks
validation
def chunks(dictionary, chunk_size): """ Yield successive n-sized chunks from dictionary. """ iterable = iter(dictionary) for __ in range(0, len(dictionary), chunk_size): yield {key: dictionary[key] for key in islice(iterable, chunk_size)}
python
{ "resource": "" }
q256756
strfdelta
validation
def strfdelta(tdelta, fmt='{D:02}d {H:02}h {M:02}m {S:02}s', input_type='timedelta'): """ Convert a datetime.timedelta object or a regular number to a custom-formatted string. This function works like the strftime() method works for datetime.datetime objects. The fmt argument allows custom formatt...
python
{ "resource": "" }
q256757
DegreedContentMetadataExporter.transform_description
validation
def transform_description(self, content_metadata_item): """ Return the transformed version of the course description. We choose one value out of the course's full description, short description, and title depending on availability and length limits. """ full_description ...
python
{ "resource": "" }
q256758
logo_path
validation
def logo_path(instance, filename): """ Delete the file if it already exist and returns the enterprise customer logo image path. Arguments: instance (:class:`.EnterpriseCustomerBrandingConfiguration`): EnterpriseCustomerBrandingConfiguration object filename (str): file to upload Returns...
python
{ "resource": "" }
q256759
EnterpriseCustomerUserManager.get_link_by_email
validation
def get_link_by_email(self, user_email): """ Return link by email. """ try: user = User.objects.get(email=user_email) try: return self.get(user_id=user.id) except EnterpriseCustomerUser.DoesNotExist: pass except ...
python
{ "resource": "" }
q256760
EnterpriseCustomerUserManager.link_user
validation
def link_user(self, enterprise_customer, user_email): """ Link user email to Enterprise Customer. If :class:`django.contrib.auth.models.User` instance with specified email does not exist, :class:`.PendingEnterpriseCustomerUser` instance is created instead. """ try: ...
python
{ "resource": "" }
q256761
EnterpriseCustomerUserManager.unlink_user
validation
def unlink_user(self, enterprise_customer, user_email): """ Unlink user email from Enterprise Customer. If :class:`django.contrib.auth.models.User` instance with specified email does not exist, :class:`.PendingEnterpriseCustomerUser` instance is deleted instead. Raises Enterpri...
python
{ "resource": "" }
q256762
EnterpriseRoleAssignmentContextMixin.enterprise_customer_uuid
validation
def enterprise_customer_uuid(self): """Get the enterprise customer uuid linked to the user.""" try: enterprise_user = EnterpriseCustomerUser.objects.get(user_id=self.user.id) except ObjectDoesNotExist: LOGGER.warning( 'User {} has a {} assignment but is no...
python
{ "resource": "" }
q256763
get_data_sharing_consent
validation
def get_data_sharing_consent(username, enterprise_customer_uuid, course_id=None, program_uuid=None): """ Get the data sharing consent object associated with a certain user, enterprise customer, and other scope. :param username: The user that grants consent :param enterprise_customer_uuid: The consent r...
python
{ "resource": "" }
q256764
get_course_data_sharing_consent
validation
def get_course_data_sharing_consent(username, course_id, enterprise_customer_uuid): """ Get the data sharing consent object associated with a certain user of a customer for a course. :param username: The user that grants consent. :param course_id: The course for which consent is granted. :param ent...
python
{ "resource": "" }
q256765
get_program_data_sharing_consent
validation
def get_program_data_sharing_consent(username, program_uuid, enterprise_customer_uuid): """ Get the data sharing consent object associated with a certain user of a customer for a program. :param username: The user that grants consent. :param program_uuid: The program for which consent is granted. :...
python
{ "resource": "" }
q256766
send_course_enrollment_statement
validation
def send_course_enrollment_statement(lrs_configuration, course_enrollment): """ Send xAPI statement for course enrollment. Arguments: lrs_configuration (XAPILRSConfiguration): XAPILRSConfiguration instance where to send statements. course_enrollment (CourseEnrollment): Course enrollment o...
python
{ "resource": "" }
q256767
send_course_completion_statement
validation
def send_course_completion_statement(lrs_configuration, user, course_overview, course_grade): """ Send xAPI statement for course completion. Arguments: lrs_configuration (XAPILRSConfiguration): XAPILRSConfiguration instance where to send statements. user (User): Django User object. ...
python
{ "resource": "" }
q256768
ContentMetadataExporter.export
validation
def export(self): """ Return the exported and transformed content metadata as a dictionary. """ content_metadata_export = {} content_metadata_items = self.enterprise_api.get_content_metadata(self.enterprise_customer) LOGGER.info('Retrieved content metadata for enterprise ...
python
{ "resource": "" }
q256769
ContentMetadataExporter._transform_item
validation
def _transform_item(self, content_metadata_item): """ Transform the provided content metadata item to the schema expected by the integrated channel. """ content_metadata_type = content_metadata_item['content_type'] transformed_item = {} for integrated_channel_schema_key, ...
python
{ "resource": "" }
q256770
DataSharingConsentView.get_consent_record
validation
def get_consent_record(self, request): """ Get the consent record relevant to the request at hand. """ username, course_id, program_uuid, enterprise_customer_uuid = self.get_required_query_params(request) return get_data_sharing_consent( username, enterpri...
python
{ "resource": "" }
q256771
DataSharingConsentView.get_required_query_params
validation
def get_required_query_params(self, request): """ Gets ``username``, ``course_id``, and ``enterprise_customer_uuid``, which are the relevant query parameters for this API endpoint. :param request: The request to this endpoint. :return: The ``username``, ``course_id``, and ``ente...
python
{ "resource": "" }
q256772
DataSharingConsentView.get_no_record_response
validation
def get_no_record_response(self, request): """ Get an HTTPResponse that can be used when there's no related EnterpriseCustomer. """ username, course_id, program_uuid, enterprise_customer_uuid = self.get_required_query_params(request) data = { self.REQUIRED_PARAM_USERN...
python
{ "resource": "" }
q256773
EnterpriseConfig.ready
validation
def ready(self): """ Perform other one-time initialization steps. """ from enterprise.signals import handle_user_post_save from django.db.models.signals import pre_migrate, post_save post_save.connect(handle_user_post_save, sender=self.auth_user_model, dispatch_uid=USER_...
python
{ "resource": "" }
q256774
EnterpriseConfig._disconnect_user_post_save_for_migrations
validation
def _disconnect_user_post_save_for_migrations(self, sender, **kwargs): # pylint: disable=unused-argument """ Handle pre_migrate signal - disconnect User post_save handler. """ from django.db.models.signals import post_save post_save.disconnect(sender=self.auth_user_model, dispat...
python
{ "resource": "" }
q256775
EnterpriseStatement.get_actor
validation
def get_actor(self, username, email): """ Get actor for the statement. """ return Agent( name=username, mbox='mailto:{email}'.format(email=email), )
python
{ "resource": "" }
q256776
EnterpriseStatement.get_object
validation
def get_object(self, name, description): """ Get object for the statement. """ return Activity( id=X_API_ACTIVITY_COURSE, definition=ActivityDefinition( name=LanguageMap({'en-US': (name or '').encode("ascii", "ignore").decode('ascii')}), ...
python
{ "resource": "" }
q256777
parse_csv
validation
def parse_csv(file_stream, expected_columns=None): """ Parse csv file and return a stream of dictionaries representing each row. First line of CSV file must contain column headers. Arguments: file_stream: input file expected_columns (set[unicode]): columns that are expected to be pre...
python
{ "resource": "" }
q256778
validate_email_to_link
validation
def validate_email_to_link(email, raw_email=None, message_template=None, ignore_existing=False): """ Validate email to be linked to Enterprise Customer. Performs two checks: * Checks that email is valid * Checks that it is not already linked to any Enterprise Customer Arguments: ...
python
{ "resource": "" }
q256779
get_course_runs_from_program
validation
def get_course_runs_from_program(program): """ Return course runs from program data. Arguments: program(dict): Program data from Course Catalog API Returns: set: course runs in given program """ course_runs = set() for course in program.get("courses", []): for run i...
python
{ "resource": "" }
q256780
get_earliest_start_date_from_program
validation
def get_earliest_start_date_from_program(program): """ Get the earliest date that one of the courses in the program was available. For the sake of emails to new learners, we treat this as the program start date. Arguemnts: program (dict): Program data from Course Catalog API returns: ...
python
{ "resource": "" }
q256781
paginated_list
validation
def paginated_list(object_list, page, page_size=25): """ Returns paginated list. Arguments: object_list (QuerySet): A list of records to be paginated. page (int): Current page number. page_size (int): Number of records displayed in each paginated set. show_all (bool): Whethe...
python
{ "resource": "" }
q256782
ManageLearnersForm.clean_email_or_username
validation
def clean_email_or_username(self): """ Clean email form field Returns: str: the cleaned value, converted to an email address (or an empty string) """ email_or_username = self.cleaned_data[self.Fields.EMAIL_OR_USERNAME].strip() if not email_or_username: ...
python
{ "resource": "" }
q256783
ManageLearnersForm.clean_course
validation
def clean_course(self): """ Verify course ID and retrieve course details. """ course_id = self.cleaned_data[self.Fields.COURSE].strip() if not course_id: return None try: client = EnrollmentApiClient() return client.get_course_details(c...
python
{ "resource": "" }
q256784
ManageLearnersForm.clean_program
validation
def clean_program(self): """ Clean program. Try obtaining program treating form value as program UUID or title. Returns: dict: Program information if program found """ program_id = self.cleaned_data[self.Fields.PROGRAM].strip() if not program_id: ...
python
{ "resource": "" }
q256785
ManageLearnersForm.clean_notify
validation
def clean_notify(self): """ Clean the notify_on_enrollment field. """ return self.cleaned_data.get(self.Fields.NOTIFY, self.NotificationTypes.DEFAULT)
python
{ "resource": "" }
q256786
ManageLearnersForm.clean
validation
def clean(self): """ Clean fields that depend on each other. In this case, the form can be used to link single user or bulk link multiple users. These are mutually exclusive modes, so this method checks that only one field is passed. """ cleaned_data = super(ManageLearne...
python
{ "resource": "" }
q256787
ManageLearnersForm._validate_course
validation
def _validate_course(self): """ Verify that the selected mode is valid for the given course . """ # Verify that the selected mode is valid for the given course . course_details = self.cleaned_data.get(self.Fields.COURSE) if course_details: course_mode = self.c...
python
{ "resource": "" }
q256788
ManageLearnersForm._validate_program
validation
def _validate_program(self): """ Verify that selected mode is available for program and all courses in the program """ program = self.cleaned_data.get(self.Fields.PROGRAM) if not program: return course_runs = get_course_runs_from_program(program) try:...
python
{ "resource": "" }
q256789
EnterpriseCustomerAdminForm.get_catalog_options
validation
def get_catalog_options(self): """ Retrieve a list of catalog ID and name pairs. Once retrieved, these name pairs can be used directly as a value for the `choices` argument to a ChoiceField. """ # TODO: We will remove the discovery service catalog implementation ...
python
{ "resource": "" }
q256790
EnterpriseCustomerAdminForm.clean
validation
def clean(self): """ Clean form fields prior to database entry. In this case, the major cleaning operation is substituting a None value for a blank value in the Catalog field. """ cleaned_data = super(EnterpriseCustomerAdminForm, self).clean() if 'catalog' in cle...
python
{ "resource": "" }
q256791
EnterpriseCustomerIdentityProviderAdminForm.clean
validation
def clean(self): """ Final validations of model fields. 1. Validate that selected site for enterprise customer matches with the selected identity provider's site. """ super(EnterpriseCustomerIdentityProviderAdminForm, self).clean() provider_id = self.cleaned_data.get('p...
python
{ "resource": "" }
q256792
EnterpriseCustomerReportingConfigAdminForm.clean
validation
def clean(self): """ Override of clean method to perform additional validation """ cleaned_data = super(EnterpriseCustomerReportingConfigAdminForm, self).clean() report_customer = cleaned_data.get('enterprise_customer') # Check that any selected catalogs are tied to the ...
python
{ "resource": "" }
q256793
TransmitEnterpriseCoursesForm.clean_channel_worker_username
validation
def clean_channel_worker_username(self): """ Clean enterprise channel worker user form field Returns: str: the cleaned value of channel user username for transmitting courses metadata. """ channel_worker_username = self.cleaned_data['channel_worker_username'].strip()...
python
{ "resource": "" }
q256794
verify_edx_resources
validation
def verify_edx_resources(): """ Ensure that all necessary resources to render the view are present. """ required_methods = { 'ProgramDataExtender': ProgramDataExtender, } for method in required_methods: if required_methods[method] is None: raise NotConnectedToOpenEdX...
python
{ "resource": "" }
q256795
get_global_context
validation
def get_global_context(request, enterprise_customer): """ Get the set of variables that are needed by default across views. """ platform_name = get_configuration_value("PLATFORM_NAME", settings.PLATFORM_NAME) # pylint: disable=no-member return { 'enterprise_customer': enterprise_customer...
python
{ "resource": "" }
q256796
render_page_with_error_code_message
validation
def render_page_with_error_code_message(request, context_data, error_code, log_message): """ Return a 404 page with specified error_code after logging error and adding message to django messages. """ LOGGER.error(log_message) messages.add_generic_error_message_with_code(request, error_code) retu...
python
{ "resource": "" }
q256797
GrantDataSharingPermissions.course_or_program_exist
validation
def course_or_program_exist(self, course_id, program_uuid): """ Return whether the input course or program exist. """ course_exists = course_id and CourseApiClient().get_course_details(course_id) program_exists = program_uuid and CourseCatalogApiServiceClient().program_exists(pro...
python
{ "resource": "" }
q256798
GrantDataSharingPermissions.get_course_or_program_context
validation
def get_course_or_program_context(self, enterprise_customer, course_id=None, program_uuid=None): """ Return a dict having course or program specific keys for data sharing consent page. """ context_data = {} if course_id: context_data.update({'course_id': course_id, 'c...
python
{ "resource": "" }
q256799
GrantDataSharingPermissions.post
validation
def post(self, request): """ Process the above form. """ enterprise_uuid = request.POST.get('enterprise_customer_uuid') success_url = request.POST.get('redirect_url') failure_url = request.POST.get('failure_url') course_id = request.POST.get('course_id', '') ...
python
{ "resource": "" }