_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q256600
AssertionBuilder.is_less_than
validation
def is_less_than(self, other): """Asserts that val is numeric and is less than other.""" self._validate_compareable(other) if self.val >= other: if type(self.val) is datetime.datetime: self._err('Expected <%s> to be less than <%s>, but was not.' % (self.val.strftime('...
python
{ "resource": "" }
q256601
AssertionBuilder.is_between
validation
def is_between(self, low, high): """Asserts that val is numeric and is between low and high.""" val_type = type(self.val) self._validate_between_args(val_type, low, high) if self.val < low or self.val > high: if val_type is datetime.datetime: self._err('Expec...
python
{ "resource": "" }
q256602
AssertionBuilder.is_close_to
validation
def is_close_to(self, other, tolerance): """Asserts that val is numeric and is close to other within tolerance.""" self._validate_close_to_args(self.val, other, tolerance) if self.val < (other-tolerance) or self.val > (other+tolerance): if type(self.val) is datetime.datetime: ...
python
{ "resource": "" }
q256603
AssertionBuilder.is_equal_to_ignoring_case
validation
def is_equal_to_ignoring_case(self, other): """Asserts that val is case-insensitive equal to other.""" if not isinstance(self.val, str_types): raise TypeError('val is not a string') if not isinstance(other, str_types): raise TypeError('given arg must be a string') ...
python
{ "resource": "" }
q256604
AssertionBuilder.contains_ignoring_case
validation
def contains_ignoring_case(self, *items): """Asserts that val is string and contains the given item or items.""" if len(items) == 0: raise ValueError('one or more args must be given') if isinstance(self.val, str_types): if len(items) == 1: if not isinstanc...
python
{ "resource": "" }
q256605
AssertionBuilder.starts_with
validation
def starts_with(self, prefix): """Asserts that val is string or iterable and starts with prefix.""" if prefix is None: raise TypeError('given prefix arg must not be none') if isinstance(self.val, str_types): if not isinstance(prefix, str_types): raise Type...
python
{ "resource": "" }
q256606
AssertionBuilder.ends_with
validation
def ends_with(self, suffix): """Asserts that val is string or iterable and ends with suffix.""" if suffix is None: raise TypeError('given suffix arg must not be none') if isinstance(self.val, str_types): if not isinstance(suffix, str_types): raise TypeErro...
python
{ "resource": "" }
q256607
AssertionBuilder.matches
validation
def matches(self, pattern): """Asserts that val is string and matches regex pattern.""" if not isinstance(self.val, str_types): raise TypeError('val is not a string') if not isinstance(pattern, str_types): raise TypeError('given pattern arg must be a string') if l...
python
{ "resource": "" }
q256608
AssertionBuilder.is_alpha
validation
def is_alpha(self): """Asserts that val is non-empty string and all characters are alphabetic.""" if not isinstance(self.val, str_types): raise TypeError('val is not a string') if len(self.val) == 0: raise ValueError('val is empty') if not self.val.isalpha(): ...
python
{ "resource": "" }
q256609
AssertionBuilder.is_digit
validation
def is_digit(self): """Asserts that val is non-empty string and all characters are digits.""" if not isinstance(self.val, str_types): raise TypeError('val is not a string') if len(self.val) == 0: raise ValueError('val is empty') if not self.val.isdigit(): ...
python
{ "resource": "" }
q256610
AssertionBuilder.is_lower
validation
def is_lower(self): """Asserts that val is non-empty string and all characters are lowercase.""" if not isinstance(self.val, str_types): raise TypeError('val is not a string') if len(self.val) == 0: raise ValueError('val is empty') if self.val != self.val.lower():...
python
{ "resource": "" }
q256611
AssertionBuilder.is_upper
validation
def is_upper(self): """Asserts that val is non-empty string and all characters are uppercase.""" if not isinstance(self.val, str_types): raise TypeError('val is not a string') if len(self.val) == 0: raise ValueError('val is empty') if self.val != self.val.upper():...
python
{ "resource": "" }
q256612
AssertionBuilder.is_unicode
validation
def is_unicode(self): """Asserts that val is a unicode string.""" if type(self.val) is not unicode: self._err('Expected <%s> to be unicode, but was <%s>.' % (self.val, type(self.val).__name__)) return self
python
{ "resource": "" }
q256613
AssertionBuilder.is_subset_of
validation
def is_subset_of(self, *supersets): """Asserts that val is iterable and a subset of the given superset or flattened superset if multiple supersets are given.""" if not isinstance(self.val, Iterable): raise TypeError('val is not iterable') if len(supersets) == 0: raise Val...
python
{ "resource": "" }
q256614
AssertionBuilder.contains_value
validation
def contains_value(self, *values): """Asserts that val is a dict and contains the given value or values.""" self._check_dict_like(self.val, check_getitem=False) if len(values) == 0: raise ValueError('one or more value args must be given') missing = [] for v in values:...
python
{ "resource": "" }
q256615
AssertionBuilder.does_not_contain_value
validation
def does_not_contain_value(self, *values): """Asserts that val is a dict and does not contain the given value or values.""" self._check_dict_like(self.val, check_getitem=False) if len(values) == 0: raise ValueError('one or more value args must be given') else: fou...
python
{ "resource": "" }
q256616
AssertionBuilder.contains_entry
validation
def contains_entry(self, *args, **kwargs): """Asserts that val is a dict and contains the given entry or entries.""" self._check_dict_like(self.val, check_values=False) entries = list(args) + [{k:v} for k,v in kwargs.items()] if len(entries) == 0: raise ValueError('one or mor...
python
{ "resource": "" }
q256617
AssertionBuilder.is_before
validation
def is_before(self, other): """Asserts that val is a date and is before other date.""" if type(self.val) is not datetime.datetime: raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__) if type(other) is not datetime.datetime: raise TypeError...
python
{ "resource": "" }
q256618
AssertionBuilder.exists
validation
def exists(self): """Asserts that val is a path and that it exists.""" if not isinstance(self.val, str_types): raise TypeError('val is not a path') if not os.path.exists(self.val): self._err('Expected <%s> to exist, but was not found.' % self.val) return self
python
{ "resource": "" }
q256619
AssertionBuilder.is_file
validation
def is_file(self): """Asserts that val is an existing path to a file.""" self.exists() if not os.path.isfile(self.val): self._err('Expected <%s> to be a file, but was not.' % self.val) return self
python
{ "resource": "" }
q256620
AssertionBuilder.is_directory
validation
def is_directory(self): """Asserts that val is an existing path to a directory.""" self.exists() if not os.path.isdir(self.val): self._err('Expected <%s> to be a directory, but was not.' % self.val) return self
python
{ "resource": "" }
q256621
AssertionBuilder.is_named
validation
def is_named(self, filename): """Asserts that val is an existing path to a file and that file is named filename.""" self.is_file() if not isinstance(filename, str_types): raise TypeError('given filename arg must be a path') val_filename = os.path.basename(os.path.abspath(self...
python
{ "resource": "" }
q256622
AssertionBuilder.is_child_of
validation
def is_child_of(self, parent): """Asserts that val is an existing path to a file and that file is a child of parent.""" self.is_file() if not isinstance(parent, str_types): raise TypeError('given parent directory arg must be a path') val_abspath = os.path.abspath(self.val) ...
python
{ "resource": "" }
q256623
AssertionBuilder.raises
validation
def raises(self, ex): """Asserts that val is callable and that when called raises the given error.""" if not callable(self.val): raise TypeError('val must be callable') if not issubclass(ex, BaseException): raise TypeError('given arg must be exception') return Ass...
python
{ "resource": "" }
q256624
AssertionBuilder.when_called_with
validation
def when_called_with(self, *some_args, **some_kwargs): """Asserts the val callable when invoked with the given args and kwargs raises the expected exception.""" if not self.expected: raise TypeError('expected exception not set, raises() must be called first') try: self.va...
python
{ "resource": "" }
q256625
AssertionBuilder._err
validation
def _err(self, msg): """Helper to raise an AssertionError, and optionally prepend custom description.""" out = '%s%s' % ('[%s] ' % self.description if len(self.description) > 0 else '', msg) if self.kind == 'warn': print(out) return self elif self.kind == 'soft': ...
python
{ "resource": "" }
q256626
AssertionBuilder._fmt_args_kwargs
validation
def _fmt_args_kwargs(self, *some_args, **some_kwargs): """Helper to convert the given args and kwargs into a string.""" if some_args: out_args = str(some_args).lstrip('(').rstrip(',)') if some_kwargs: out_kwargs = ', '.join([str(i).lstrip('(').rstrip(')').replace(', ',': ...
python
{ "resource": "" }
q256627
create_char_dataframe
validation
def create_char_dataframe(words): """ Give list of input tokenized words, create dataframe of characters where first character of the word is tagged as 1, otherwise 0 Example ======= ['กิน', 'หมด'] to dataframe of [{'char': 'ก', 'type': ..., 'target': 1}, ..., {'char': 'ด', 'type':...
python
{ "resource": "" }
q256628
generate_best_dataset
validation
def generate_best_dataset(best_path, output_path='cleaned_data', create_val=False): """ Generate CSV file for training and testing data Input ===== best_path: str, path to BEST folder which contains unzipped subfolder 'article', 'encyclopedia', 'news', 'novel' cleaned_data: str, path t...
python
{ "resource": "" }
q256629
prepare_feature
validation
def prepare_feature(best_processed_path, option='train'): """ Transform processed path into feature matrix and output array Input ===== best_processed_path: str, path to processed BEST dataset option: str, 'train' or 'test' """ # padding for training and testing set n_pad = 21 ...
python
{ "resource": "" }
q256630
train_model
validation
def train_model(best_processed_path, weight_path='../weight/model_weight.h5', verbose=2): """ Given path to processed BEST dataset, train CNN model for words beginning alongside with character label encoder and character type label encoder Input ===== best_processed_path: str, path to proce...
python
{ "resource": "" }
q256631
evaluate
validation
def evaluate(best_processed_path, model): """ Evaluate model on splitted 10 percent testing set """ x_test_char, x_test_type, y_test = prepare_feature(best_processed_path, option='test') y_predict = model.predict([x_test_char, x_test_type]) y_predict = (y_predict.ravel() > 0.5).astype(int) ...
python
{ "resource": "" }
q256632
tokenize
validation
def tokenize(text, custom_dict=None): """ Tokenize given Thai text string Input ===== text: str, Thai text string custom_dict: str (or list), path to customized dictionary file It allows the function not to tokenize given dictionary wrongly. The file should contain custom words ...
python
{ "resource": "" }
q256633
_document_frequency
validation
def _document_frequency(X): """ Count the number of non-zero values for each feature in sparse X. """ if sp.isspmatrix_csr(X): return np.bincount(X.indices, minlength=X.shape[1]) return np.diff(sp.csc_matrix(X, copy=False).indptr)
python
{ "resource": "" }
q256634
DeepcutTokenizer._word_ngrams
validation
def _word_ngrams(self, tokens): """ Turn tokens into a tokens of n-grams ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153 """ # handle stop words if self.stop_words is not None: tokens = [w for w in ...
python
{ "resource": "" }
q256635
create_feature_array
validation
def create_feature_array(text, n_pad=21): """ Create feature array of character and surrounding characters """ n = len(text) n_pad_2 = int((n_pad - 1)/2) text_pad = [' '] * n_pad_2 + [t for t in text] + [' '] * n_pad_2 x_char, x_type = [], [] for i in range(n_pad_2, n_pad_2 + n): ...
python
{ "resource": "" }
q256636
create_n_gram_df
validation
def create_n_gram_df(df, n_pad): """ Given input dataframe, create feature dataframe of shifted characters """ n_pad_2 = int((n_pad - 1)/2) for i in range(n_pad_2): df['char-{}'.format(i+1)] = df['char'].shift(i + 1) df['type-{}'.format(i+1)] = df['type'].shift(i + 1) df['cha...
python
{ "resource": "" }
q256637
Command._dictfetchall
validation
def _dictfetchall(self, cursor): """ Return all rows from a cursor as a dict. """ columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ]
python
{ "resource": "" }
q256638
parse_lms_api_datetime
validation
def parse_lms_api_datetime(datetime_string, datetime_format=LMS_API_DATETIME_FORMAT): """ Parse a received datetime into a timezone-aware, Python datetime object. Arguments: datetime_string: A string to be parsed. datetime_format: A datetime format string to be used for parsing """ ...
python
{ "resource": "" }
q256639
JwtLmsApiClient.connect
validation
def connect(self): """ Connect to the REST API, authenticating with a JWT for the current user. """ if JwtBuilder is None: raise NotConnectedToOpenEdX("This package must be installed in an OpenEdX environment.") now = int(time()) jwt = JwtBuilder.create_jwt_f...
python
{ "resource": "" }
q256640
JwtLmsApiClient.refresh_token
validation
def refresh_token(func): """ Use this method decorator to ensure the JWT token is refreshed when needed. """ @wraps(func) def inner(self, *args, **kwargs): """ Before calling the wrapped function, we check if the JWT token is expired, and if so, re-connect...
python
{ "resource": "" }
q256641
EmbargoApiClient.redirect_if_blocked
validation
def redirect_if_blocked(course_run_ids, user=None, ip_address=None, url=None): """ Return redirect to embargo error page if the given user is blocked. """ for course_run_id in course_run_ids: redirect_url = embargo_api.redirect_if_blocked( CourseKey.from_strin...
python
{ "resource": "" }
q256642
EnrollmentApiClient.get_course_details
validation
def get_course_details(self, course_id): """ Query the Enrollment API for the course details of the given course_id. Args: course_id (str): The string value of the course's unique identifier Returns: dict: A dictionary containing details about the course, in an ...
python
{ "resource": "" }
q256643
EnrollmentApiClient._sort_course_modes
validation
def _sort_course_modes(self, modes): """ Sort the course mode dictionaries by slug according to the COURSE_MODE_SORT_ORDER constant. Arguments: modes (list): A list of course mode dictionaries. Returns: list: A list with the course modes dictionaries sorted by sl...
python
{ "resource": "" }
q256644
EnrollmentApiClient.get_course_modes
validation
def get_course_modes(self, course_id): """ Query the Enrollment API for the specific course modes that are available for the given course_id. Arguments: course_id (str): The string value of the course's unique identifier Returns: list: A list of course mode dict...
python
{ "resource": "" }
q256645
EnrollmentApiClient.has_course_mode
validation
def has_course_mode(self, course_run_id, mode): """ Query the Enrollment API to see whether a course run has a given course mode available. Arguments: course_run_id (str): The string value of the course run's unique identifier Returns: bool: Whether the course r...
python
{ "resource": "" }
q256646
EnrollmentApiClient.enroll_user_in_course
validation
def enroll_user_in_course(self, username, course_id, mode, cohort=None): """ Call the enrollment API to enroll the user in the course specified by course_id. Args: username (str): The username by which the user goes on the OpenEdX platform course_id (str): The string val...
python
{ "resource": "" }
q256647
EnrollmentApiClient.get_course_enrollment
validation
def get_course_enrollment(self, username, course_id): """ Query the enrollment API to get information about a single course enrollment. Args: username (str): The username by which the user goes on the OpenEdX platform course_id (str): The string value of the course's uni...
python
{ "resource": "" }
q256648
EnrollmentApiClient.is_enrolled
validation
def is_enrolled(self, username, course_run_id): """ Query the enrollment API and determine if a learner is enrolled in a course run. Args: username (str): The username by which the user goes on the OpenEdX platform course_run_id (str): The string value of the course's un...
python
{ "resource": "" }
q256649
ThirdPartyAuthApiClient._get_results
validation
def _get_results(self, identity_provider, param_name, param_value, result_field_name): """ Calls the third party auth api endpoint to get the mapping between usernames and remote ids. """ try: kwargs = {param_name: param_value} returned = self.client.providers(ide...
python
{ "resource": "" }
q256650
GradesApiClient.get_course_grade
validation
def get_course_grade(self, course_id, username): """ Retrieve the grade for the given username for the given course_id. Args: * ``course_id`` (str): The string value of the course's unique identifier * ``username`` (str): The username ID identifying the user for which to retriev...
python
{ "resource": "" }
q256651
CertificatesApiClient.get_course_certificate
validation
def get_course_certificate(self, course_id, username): """ Retrieve the certificate for the given username for the given course_id. Args: * ``course_id`` (str): The string value of the course's unique identifier * ``username`` (str): The username ID identifying the user for whic...
python
{ "resource": "" }
q256652
course_discovery_api_client
validation
def course_discovery_api_client(user, catalog_url): """ Return a Course Discovery API client setup with authentication for the specified user. """ if JwtBuilder is None: raise NotConnectedToOpenEdX( _("To get a Catalog API client, this package must be " "installed in an...
python
{ "resource": "" }
q256653
CourseCatalogApiClient.traverse_pagination
validation
def traverse_pagination(response, endpoint, content_filter_query, query_params): """ Traverse a paginated API response and extracts and concatenates "results" returned by API. Arguments: response (dict): API response object. endpoint (Slumber.Resource): API endpoint obje...
python
{ "resource": "" }
q256654
CourseCatalogApiClient.get_catalog
validation
def get_catalog(self, catalog_id): """ Return specified course catalog. Returns: dict: catalog details if it is available for the user. """ return self._load_data( self.CATALOGS_ENDPOINT, default=[], resource_id=catalog_id ...
python
{ "resource": "" }
q256655
CourseCatalogApiClient.get_paginated_catalog_courses
validation
def get_paginated_catalog_courses(self, catalog_id, querystring=None): """ Return paginated response for all catalog courses. Returns: dict: API response with links to next and previous pages. """ return self._load_data( self.CATALOGS_COURSES_ENDPOINT.fo...
python
{ "resource": "" }
q256656
CourseCatalogApiClient.get_paginated_catalogs
validation
def get_paginated_catalogs(self, querystring=None): """ Return a paginated list of course catalogs, including name and ID. Returns: dict: Paginated response containing catalogs available for the user. """ return self._load_data( self.CATALOGS_ENDPOINT, ...
python
{ "resource": "" }
q256657
CourseCatalogApiClient.get_catalog_courses
validation
def get_catalog_courses(self, catalog_id): """ Return the courses included in a single course catalog by ID. Args: catalog_id (int): The catalog ID we want to retrieve. Returns: list: Courses of the catalog in question """ return self._load_data...
python
{ "resource": "" }
q256658
CourseCatalogApiClient.get_course_and_course_run
validation
def get_course_and_course_run(self, course_run_id): """ Return the course and course run metadata for the given course run ID. Arguments: course_run_id (str): The course run ID. Returns: tuple: The course metadata and the course run metadata. """ ...
python
{ "resource": "" }
q256659
CourseCatalogApiClient.get_course_details
validation
def get_course_details(self, course_id): """ Return the details of a single course by id - not a course run id. Args: course_id (str): The unique id for the course in question. Returns: dict: Details of the course in question. """ return self._l...
python
{ "resource": "" }
q256660
CourseCatalogApiClient.get_program_by_title
validation
def get_program_by_title(self, program_title): """ Return single program by name, or None if not found. Arguments: program_title(string): Program title as seen by students and in Course Catalog Admin Returns: dict: Program data provided by Course Catalog API ...
python
{ "resource": "" }
q256661
CourseCatalogApiClient.get_program_by_uuid
validation
def get_program_by_uuid(self, program_uuid): """ Return single program by UUID, or None if not found. Arguments: program_uuid(string): Program UUID in string form Returns: dict: Program data provided by Course Catalog API """ return self._load_d...
python
{ "resource": "" }
q256662
CourseCatalogApiClient.get_program_type_by_slug
validation
def get_program_type_by_slug(self, slug): """ Get a program type by its slug. Arguments: slug (str): The slug to identify the program type. Returns: dict: A program type object. """ return self._load_data( self.PROGRAM_TYPES_ENDPOINT...
python
{ "resource": "" }
q256663
CourseCatalogApiClient.get_common_course_modes
validation
def get_common_course_modes(self, course_run_ids): """ Find common course modes for a set of course runs. This function essentially returns an intersection of types of seats available for each course run. Arguments: course_run_ids(Iterable[str]): Target Course run I...
python
{ "resource": "" }
q256664
CourseCatalogApiClient.is_course_in_catalog
validation
def is_course_in_catalog(self, catalog_id, course_id): """ Determine if the given course or course run ID is contained in the catalog with the given ID. Args: catalog_id (int): The ID of the catalog course_id (str): The ID of the course or course run Returns: ...
python
{ "resource": "" }
q256665
CourseCatalogApiClient._load_data
validation
def _load_data(self, resource, default=DEFAULT_VALUE_SAFEGUARD, **kwargs): """ Load data from API client. Arguments: resource(string): type of resource to load default(any): value to return if API query returned empty result. Sensible values: [], {}, None etc. R...
python
{ "resource": "" }
q256666
EnterpriseApiClient.get_content_metadata
validation
def get_content_metadata(self, enterprise_customer): """ Return all content metadata contained in the catalogs associated with the EnterpriseCustomer. Arguments: enterprise_customer (EnterpriseCustomer): The EnterpriseCustomer to return content metadata for. Returns: ...
python
{ "resource": "" }
q256667
EnterpriseApiClient._load_data
validation
def _load_data( self, resource, detail_resource=None, resource_id=None, querystring=None, traverse_pagination=False, default=DEFAULT_VALUE_SAFEGUARD, ): """ Loads a response from a call to one of the Enterprise endpo...
python
{ "resource": "" }
q256668
ContentMetadataTransmitter._partition_items
validation
def _partition_items(self, channel_metadata_item_map): """ Return items that need to be created, updated, and deleted along with the current ContentMetadataItemTransmissions. """ items_to_create = {} items_to_update = {} items_to_delete = {} transmission_m...
python
{ "resource": "" }
q256669
ContentMetadataTransmitter._serialize_items
validation
def _serialize_items(self, channel_metadata_items): """ Serialize content metadata items for a create transmission to the integrated channel. """ return json.dumps( self._prepare_items_for_transmission(channel_metadata_items), sort_keys=True ).encode('utf-...
python
{ "resource": "" }
q256670
ContentMetadataTransmitter._transmit_create
validation
def _transmit_create(self, channel_metadata_item_map): """ Transmit content metadata creation to integrated channel. """ for chunk in chunks(channel_metadata_item_map, self.enterprise_configuration.transmission_chunk_size): serialized_chunk = self._serialize_items(list(chunk....
python
{ "resource": "" }
q256671
ContentMetadataTransmitter._transmit_update
validation
def _transmit_update(self, channel_metadata_item_map, transmission_map): """ Transmit content metadata update to integrated channel. """ for chunk in chunks(channel_metadata_item_map, self.enterprise_configuration.transmission_chunk_size): serialized_chunk = self._serialize_i...
python
{ "resource": "" }
q256672
ContentMetadataTransmitter._transmit_delete
validation
def _transmit_delete(self, channel_metadata_item_map): """ Transmit content metadata deletion to integrated channel. """ for chunk in chunks(channel_metadata_item_map, self.enterprise_configuration.transmission_chunk_size): serialized_chunk = self._serialize_items(list(chunk....
python
{ "resource": "" }
q256673
ContentMetadataTransmitter._get_transmissions
validation
def _get_transmissions(self): """ Return the ContentMetadataItemTransmision models for previously transmitted content metadata items. """ # pylint: disable=invalid-name ContentMetadataItemTransmission = apps.get_model( 'integrated_channel', 'Conten...
python
{ "resource": "" }
q256674
ContentMetadataTransmitter._create_transmissions
validation
def _create_transmissions(self, content_metadata_item_map): """ Create ContentMetadataItemTransmision models for the given content metadata items. """ # pylint: disable=invalid-name ContentMetadataItemTransmission = apps.get_model( 'integrated_channel', 'C...
python
{ "resource": "" }
q256675
ContentMetadataTransmitter._update_transmissions
validation
def _update_transmissions(self, content_metadata_item_map, transmission_map): """ Update ContentMetadataItemTransmision models for the given content metadata items. """ for content_id, channel_metadata in content_metadata_item_map.items(): transmission = transmission_map[cont...
python
{ "resource": "" }
q256676
ContentMetadataTransmitter._delete_transmissions
validation
def _delete_transmissions(self, content_metadata_item_ids): """ Delete ContentMetadataItemTransmision models associated with the given content metadata items. """ # pylint: disable=invalid-name ContentMetadataItemTransmission = apps.get_model( 'integrated_channel', ...
python
{ "resource": "" }
q256677
deprecated
validation
def deprecated(extra): """ Flag a method as deprecated. :param extra: Extra text you'd like to display after the default text. """ def decorator(func): """ Return a decorated function that emits a deprecation warning on use. """ @wraps(func) def wrapper(*args...
python
{ "resource": "" }
q256678
ignore_warning
validation
def ignore_warning(warning): """ Ignore any emitted warnings from a function. :param warning: The category of warning to ignore. """ def decorator(func): """ Return a decorated function whose emitted warnings are ignored. """ @wraps(func) def wrapper(*args, *...
python
{ "resource": "" }
q256679
enterprise_login_required
validation
def enterprise_login_required(view): """ View decorator for allowing authenticated user with valid enterprise UUID. This decorator requires enterprise identifier as a parameter `enterprise_uuid`. This decorator will throw 404 if no kwarg `enterprise_uuid` is provided to the decorated view . ...
python
{ "resource": "" }
q256680
force_fresh_session
validation
def force_fresh_session(view): """ View decorator which terminates stale TPA sessions. This decorator forces the user to obtain a new session the first time they access the decorated view. This prevents TPA-authenticated users from hijacking the session of another user who may have been previou...
python
{ "resource": "" }
q256681
EnterpriseCourseEnrollmentWriteSerializer.validate_username
validation
def validate_username(self, value): """ Verify that the username has a matching user, and that the user has an associated EnterpriseCustomerUser. """ try: user = User.objects.get(username=value) except User.DoesNotExist: raise serializers.ValidationError("...
python
{ "resource": "" }
q256682
EnterpriseCourseEnrollmentWriteSerializer.save
validation
def save(self): # pylint: disable=arguments-differ """ Save the model with the found EnterpriseCustomerUser. """ course_id = self.validated_data['course_id'] __, created = models.EnterpriseCourseEnrollment.objects.get_or_create( enterprise_customer_user=self.enterpr...
python
{ "resource": "" }
q256683
EnterpriseCustomerCatalogDetailSerializer.to_representation
validation
def to_representation(self, instance): """ Serialize the EnterpriseCustomerCatalog object. Arguments: instance (EnterpriseCustomerCatalog): The EnterpriseCustomerCatalog to serialize. Returns: dict: The EnterpriseCustomerCatalog converted to a dict. """ ...
python
{ "resource": "" }
q256684
EnterpriseCustomerUserReadOnlySerializer.get_groups
validation
def get_groups(self, obj): """ Return the enterprise related django groups that this user is a part of. """ if obj.user: return [group.name for group in obj.user.groups.filter(name__in=ENTERPRISE_PERMISSION_GROUPS)] return []
python
{ "resource": "" }
q256685
EnterpriseCustomerUserWriteSerializer.validate_username
validation
def validate_username(self, value): """ Verify that the username has a matching user. """ try: self.user = User.objects.get(username=value) except User.DoesNotExist: raise serializers.ValidationError("User does not exist") return value
python
{ "resource": "" }
q256686
EnterpriseCustomerUserWriteSerializer.save
validation
def save(self): # pylint: disable=arguments-differ """ Save the EnterpriseCustomerUser. """ enterprise_customer = self.validated_data['enterprise_customer'] ecu = models.EnterpriseCustomerUser( user_id=self.user.pk, enterprise_customer=enterprise_custome...
python
{ "resource": "" }
q256687
CourseDetailSerializer.to_representation
validation
def to_representation(self, instance): """ Return the updated course data dictionary. Arguments: instance (dict): The course data. Returns: dict: The updated course data. """ updated_course = copy.deepcopy(instance) enterprise_customer_ca...
python
{ "resource": "" }
q256688
CourseRunDetailSerializer.to_representation
validation
def to_representation(self, instance): """ Return the updated course run data dictionary. Arguments: instance (dict): The course run data. Returns: dict: The updated course run data. """ updated_course_run = copy.deepcopy(instance) enterp...
python
{ "resource": "" }
q256689
ProgramDetailSerializer.to_representation
validation
def to_representation(self, instance): """ Return the updated program data dictionary. Arguments: instance (dict): The program data. Returns: dict: The updated program data. """ updated_program = copy.deepcopy(instance) enterprise_custome...
python
{ "resource": "" }
q256690
EnterpriseCustomerCourseEnrollmentsListSerializer.to_internal_value
validation
def to_internal_value(self, data): """ This implements the same relevant logic as ListSerializer except that if one or more items fail validation, processing for other items that did not fail will continue. """ if not isinstance(data, list): message = self.error_mess...
python
{ "resource": "" }
q256691
EnterpriseCustomerCourseEnrollmentsListSerializer.create
validation
def create(self, validated_data): """ This selectively calls the child create method based on whether or not validation failed for each payload. """ ret = [] for attrs in validated_data: if 'non_field_errors' not in attrs and not any(isinstance(attrs[field], list) for...
python
{ "resource": "" }
q256692
EnterpriseCustomerCourseEnrollmentsListSerializer.to_representation
validation
def to_representation(self, data): """ This selectively calls to_representation on each result that was processed by create. """ return [ self.child.to_representation(item) if 'detail' in item else item for item in data ]
python
{ "resource": "" }
q256693
EnterpriseCustomerCourseEnrollmentsSerializer.create
validation
def create(self, validated_data): """ Perform the enrollment for existing enterprise customer users, or create the pending objects for new users. """ enterprise_customer = self.context.get('enterprise_customer') lms_user = validated_data.get('lms_user_id') tpa_user = vali...
python
{ "resource": "" }
q256694
EnterpriseCustomerCourseEnrollmentsSerializer.validate_lms_user_id
validation
def validate_lms_user_id(self, value): """ Validates the lms_user_id, if is given, to see if there is an existing EnterpriseCustomerUser for it. """ enterprise_customer = self.context.get('enterprise_customer') try: # Ensure the given user is associated with the ente...
python
{ "resource": "" }
q256695
EnterpriseCustomerCourseEnrollmentsSerializer.validate_tpa_user_id
validation
def validate_tpa_user_id(self, value): """ Validates the tpa_user_id, if is given, to see if there is an existing EnterpriseCustomerUser for it. It first uses the third party auth api to find the associated username to do the lookup. """ enterprise_customer = self.context.get('e...
python
{ "resource": "" }
q256696
EnterpriseCustomerCourseEnrollmentsSerializer.validate_user_email
validation
def validate_user_email(self, value): """ Validates the user_email, if given, to see if an existing EnterpriseCustomerUser exists for it. If it does not, it does not fail validation, unlike for the other field validation methods above. """ enterprise_customer = self.context.get(...
python
{ "resource": "" }
q256697
EnterpriseCustomerCourseEnrollmentsSerializer.validate_course_run_id
validation
def validate_course_run_id(self, value): """ Validates that the course run id is part of the Enterprise Customer's catalog. """ enterprise_customer = self.context.get('enterprise_customer') if not enterprise_customer.catalog_contains_course(value): raise serializers....
python
{ "resource": "" }
q256698
EnterpriseCustomerCourseEnrollmentsSerializer.validate
validation
def validate(self, data): # pylint: disable=arguments-differ """ Validate that at least one of the user identifier fields has been passed in. """ lms_user_id = data.get('lms_user_id') tpa_user_id = data.get('tpa_user_id') user_email = data.get('user_email') if no...
python
{ "resource": "" }
q256699
get_paginated_response
validation
def get_paginated_response(data, request): """ Update pagination links in course catalog data and return DRF Response. Arguments: data (dict): Dictionary containing catalog courses. request (HttpRequest): Current request object. Returns: (Response): DRF response object containi...
python
{ "resource": "" }