_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | 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> | 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 | 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:
tolerance_seconds = tolerance.days * 86400 + tolerance.seconds + tolerance.microseconds / 1000000
h, rem = divmod(tolerance_seconds, 3600)
m, s = divmod(rem, 60)
self._err('Expected <%s> to be close to <%s> | 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 isinstance(items[0], str_types):
raise TypeError('given arg must be a string')
if items[0].lower() not in self.val.lower():
self._err('Expected <%s> to case-insensitive contain item <%s>, but did not.' % (self.val, items[0]))
else:
missing = []
for i in items:
if not isinstance(i, str_types):
raise TypeError('given args must all be strings')
if i.lower() not in self.val.lower():
missing.append(i)
if missing:
self._err('Expected <%s> to case-insensitive contain items %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing)))
elif isinstance(self.val, Iterable):
missing = []
for i in items: | 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 TypeError('given prefix arg must be a string')
if len(prefix) == 0:
raise ValueError('given prefix arg must not be empty')
if not self.val.startswith(prefix):
self._err('Expected <%s> to start with <%s>, but did not.' % (self.val, prefix))
elif isinstance(self.val, Iterable):
| 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 TypeError('given suffix arg must be a string')
if len(suffix) == 0:
raise ValueError('given suffix arg must not be empty')
if not self.val.endswith(suffix):
self._err('Expected <%s> to end with <%s>, but did not.' % (self.val, suffix))
elif isinstance(self.val, Iterable):
if | 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 len(pattern) == 0:
| 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')
| 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')
| 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')
| 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')
| 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 | 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 ValueError('one or more superset args must be given')
missing = []
if hasattr(self.val, 'keys') and callable(getattr(self.val, 'keys')) and hasattr(self.val, '__getitem__'):
# flatten superset dicts
superdict = {}
for l,j in enumerate(supersets):
self._check_dict_like(j, check_values=False, name='arg #%d' % (l+1))
for k in j.keys():
superdict.update({k: j[k]})
for i in self.val.keys():
if i not in superdict:
missing.append({i: self.val[i]}) # bad key
elif self.val[i] != superdict[i]:
missing.append({i: self.val[i]}) # bad val
if missing:
| 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:
if v not in self.val.values():
missing.append(v)
if | 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:
found = []
for v in values:
if v in self.val.values():
| 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 more entry args must be given')
missing = []
for e in entries:
| 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('given arg must be datetime, but was type <%s>' % | 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):
| 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):
| 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):
| 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.val))
| 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)
parent_abspath = os.path.abspath(parent)
| 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 | 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.val(*some_args, **some_kwargs)
except BaseException as e:
if issubclass(type(e), self.expected):
# chain on with exception message as val
| 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)
| 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(', ',': ') for i in [
(k,some_kwargs[k]) for k in sorted(some_kwargs.keys())]])
| 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': ..., 'target': 0}]
"""
char_dict = []
for word in words:
for i, char in enumerate(word):
if i == 0:
char_dict.append({'char': char,
| 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 to output folder, the cleaned data will be saved
in the given folder name where training set will be stored in `train` folder
and testing set will be stored on `test` folder
create_val: boolean, True or False, if True, divide training set into training set and
validation set in `val` folder
"""
if not os.path.isdir(output_path):
os.mkdir(output_path)
if not os.path.isdir(os.path.join(output_path, 'train')):
os.makedirs(os.path.join(output_path, 'train'))
if not os.path.isdir(os.path.join(output_path, 'test')):
os.makedirs(os.path.join(output_path, 'test'))
if not os.path.isdir(os.path.join(output_path, 'val')) and create_val:
os.makedirs(os.path.join(output_path, 'val'))
for article_type in article_types:
files = glob(os.path.join(best_path, article_type, '*.txt'))
files_train, files_test = train_test_split(files, random_state=0, test_size=0.1)
| 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
n_pad_2 = int((n_pad - 1)/2)
pad = [{'char': ' ', 'type': 'p', 'target': True}]
df_pad = pd.DataFrame(pad * n_pad_2)
df = []
for article_type in article_types:
df.append(pd.read_csv(os.path.join(best_processed_path, option, 'df_best_{}_{}.csv'.format(article_type, option))))
| 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 processed BEST dataset
weight_path: str, path to weight path file
verbose: int, verbost option for training Keras model
Output
======
model: keras model, keras model for tokenize prediction
"""
x_train_char, x_train_type, y_train = prepare_feature(best_processed_path, option='train')
x_test_char, x_test_type, y_test = prepare_feature(best_processed_path, option='test')
validation_set = False
if os.path.isdir(os.path.join(best_processed_path, 'val')):
validation_set = True
x_val_char, x_val_type, y_val = prepare_feature(best_processed_path, option='val')
if not os.path.isdir(os.path.dirname(weight_path)):
os.makedirs(os.path.dirname(weight_path)) # make directory if weight does not exist
callbacks_list = [
ReduceLROnPlateau(),
ModelCheckpoint(
weight_path,
save_best_only=True,
save_weights_only=True,
monitor='val_loss',
mode='min',
verbose=1
)
| 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 separated by line.
Alternatively, you can provide list of custom words too.
Output
======
| 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):
| 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 tokens if w not in self.stop_words]
# handle token n-grams
min_n, max_n = self.ngram_range
if max_n != 1:
original_tokens = tokens
if min_n == 1:
# no need to do any slicing for unigrams
# just iterate through the original tokens
tokens = list(original_tokens)
min_n += 1
else:
tokens = []
| 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):
char_list = text_pad[i + 1: i + n_pad_2 + 1] + \
list(reversed(text_pad[i - n_pad_2: i])) + \
[text_pad[i]]
char_map = [CHARS_MAP.get(c, 80) for c in | 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):
| 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 [
| 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
"""
if isinstance(datetime_string, datetime.datetime):
date_time = datetime_string
| 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_for_user(self.user)
| 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 | 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_string(course_run_id),
| 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 enrollment context (allowed modes, etc.)
"""
try:
| 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 slug.
"""
def slug_weight(mode):
"""
Assign a weight to the course mode dictionary based on the position of its slug in the sorting list.
"""
sorting_slugs = COURSE_MODE_SORT_ORDER | 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 dictionaries.
| 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 run has the | 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 value of the course's unique identifier
mode (str): The enrollment mode which should be used for the enrollment
cohort (str): Add the user to this named cohort
Returns:
dict: A dictionary containing details of | 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 unique identifier
Returns:
dict: A dictionary containing details of the enrollment, including course details, mode, username, etc.
"""
endpoint = getattr(
self.client.enrollment,
'{username},{course_id}'.format(username=username, course_id=course_id)
)
try:
result = endpoint.get()
except HttpNotFoundError:
# This enrollment data endpoint returns a 404 if either the username or course_id specified isn't valid | 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 unique identifier
Returns:
| 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(identity_provider).users.get(**kwargs)
results = returned.get('results', [])
except HttpNotFoundError:
LOGGER.error(
'username not found for third party provider={provider}, {querystring_param}={id}'.format(
| 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 retrieve the grade.
Raises:
HttpNotFoundError if no grade found for the given user+course.
Returns:
a dict containing:
* ``username``: A string representation of a user's username passed in the request.
* ``course_key``: A string representation of a Course ID.
* ``passed``: Boolean representing whether the course has been passed according the course's grading policy.
* ``percent``: A float representing the overall grade for the course
| 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 which to retrieve the certificate
Raises:
HttpNotFoundError if no certificate found for the given user+course.
Returns:
a dict containing:
* ``username``: A string representation of an user's username passed in the request.
* ``course_id``: A string representation of a Course ID.
* ``certificate_type``: A string representation of the certificate type.
* ``created_date`: Datetime the certificate was created (tz-aware).
| 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 "
| 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 object.
content_filter_query (dict): query parameters used to filter catalog results.
query_params (dict): query parameters used to paginate results.
Returns:
list: all the results returned by the API.
"""
| 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(
| 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(
| 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(
| 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 | 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.
"""
# Parse the course ID from the course run ID.
course_id = parse_course_key(course_run_id)
# Retrieve the course metadata from the catalog service.
course = self.get_course_details(course_id)
course_run = None
if course:
| 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. | 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
"""
all_programs = self._load_data(self.PROGRAMS_ENDPOINT, default=[])
matching_programs = [program | 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
| 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.
| 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 IDs.
Returns:
set: course modes found in all given course runs
Examples:
# run1 has prof and audit, run 2 has the same
get_common_course_modes(['course-v1:run1', 'course-v1:run2'])
{'prof', 'audit'}
# run1 has prof and audit, run 2 has only prof
get_common_course_modes(['course-v1:run1', 'course-v1:run2'])
{'prof'}
# run1 has prof and audit, run 2 honor
get_common_course_modes(['course-v1:run1', 'course-v1:run2'])
{}
# run1 has nothing, run2 has prof
get_common_course_modes(['course-v1:run1', 'course-v1:run2'])
{}
# run1 has prof and audit, run 2 prof, run3 has audit
get_common_course_modes(['course-v1:run1', 'course-v1:run2', 'course-v1:run3'])
{}
# | 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:
bool: Whether the course or course run is contained in the given catalog
"""
try:
# Determine if we have a course run ID, rather than a plain course ID
course_run_id = str(CourseKey.from_string(course_id))
| 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.
Returns:
dict: Deserialized response from Course Catalog API
"""
default_val = default if default != self.DEFAULT_VALUE_SAFEGUARD else {}
try:
return get_edx_api_data(
api_config=CatalogIntegration.current(),
| 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:
list: List of dicts containing content metadata.
"""
content_metadata = OrderedDict()
# TODO: This if block can be removed when we get rid of discovery service-based catalogs.
if enterprise_customer.catalog:
response = self._load_data(
self.ENTERPRISE_CUSTOMER_ENDPOINT,
detail_resource='courses',
resource_id=str(enterprise_customer.uuid),
traverse_pagination=True,
)
for course in response['results']:
for course_run in course['course_runs']:
course_run['content_type'] = 'courserun' # Make this look like a search endpoint result.
content_metadata[course_run['key']] = course_run
| 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 endpoints.
:param resource: The endpoint resource name.
:param detail_resource: The sub-resource to append to the path.
:param resource_id: The resource ID for the specific detail to get from the endpoint.
:param querystring: Optional query string parameters.
:param traverse_pagination: Whether to traverse pagination or return paginated response.
:param default: The default value to return in case of no response content.
:return: Data returned by the API.
"""
default_val = default if default != self.DEFAULT_VALUE_SAFEGUARD else {}
querystring = querystring if querystring else {}
cache_key = utils.get_cache_key(
resource=resource,
querystring=querystring,
traverse_pagination=traverse_pagination,
resource_id=resource_id
)
response = cache.get(cache_key)
if not response:
| 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_map = {}
export_content_ids = channel_metadata_item_map.keys()
# Get the items that were previously transmitted to the integrated channel.
# If we are not transmitting something that was previously transmitted,
# we need to delete it from the integrated channel.
for transmission in self._get_transmissions():
transmission_map[transmission.content_id] = transmission
if transmission.content_id not in export_content_ids:
items_to_delete[transmission.content_id] = transmission.channel_metadata
# Compare what is currently being transmitted to what was transmitted
# previously, identifying items that need to be created or updated.
for item in channel_metadata_item_map.values():
content_id = item.content_id
channel_metadata = item.channel_metadata
transmitted_item = transmission_map.get(content_id, None)
if transmitted_item is not None:
if diff(channel_metadata, transmitted_item.channel_metadata):
items_to_update[content_id] = channel_metadata
| python | {
"resource": ""
} |
q256669 | ContentMetadataTransmitter._serialize_items | validation | def _serialize_items(self, channel_metadata_items):
"""
Serialize content metadata items for a create transmission to the | 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.values()))
try:
self.client.create_content_metadata(serialized_chunk)
except ClientError as exc:
LOGGER.error(
'Failed to update [%s] content metadata items | 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_items(list(chunk.values()))
try:
self.client.update_content_metadata(serialized_chunk)
except ClientError as exc:
LOGGER.error(
'Failed to update [%s] content | 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.values()))
try:
self.client.delete_content_metadata(serialized_chunk)
except ClientError as exc:
LOGGER.error(
'Failed to delete [%s] content metadata items for integrated channel | 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',
'ContentMetadataItemTransmission'
| 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',
'ContentMetadataItemTransmission'
)
transmissions = []
for content_id, channel_metadata in content_metadata_item_map.items():
transmissions.append(
ContentMetadataItemTransmission(
enterprise_customer=self.enterprise_configuration.enterprise_customer,
| 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.
| 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',
'ContentMetadataItemTransmission'
) | 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, **kwargs):
"""
Wrap the function.
"""
message = 'You called the deprecated function `{function}`. {extra}'.format(
function=func.__name__,
extra=extra
| 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, **kwargs):
| 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 .
If there is no enterprise in database against the kwarg `enterprise_uuid`
or if the user is not authenticated then it will redirect the user to the
enterprise-linked SSO login page.
Usage::
@enterprise_login_required()
def my_view(request, enterprise_uuid):
# Some functionality ...
OR
class MyView(View):
...
@method_decorator(enterprise_login_required)
def get(self, request, enterprise_uuid):
# Some functionality ...
"""
@wraps(view)
def wrapper(request, *args, **kwargs):
"""
Wrap the decorator.
"""
if 'enterprise_uuid' not in kwargs:
raise Http404
enterprise_uuid = kwargs['enterprise_uuid']
enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid)
# Now verify if the user is logged in. If user is not logged in then
# send the user to the login screen to sign in with an
# Enterprise-linked IdP and the pipeline will get them back here.
if not | 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 previously logged in using the same
browser window.
This decorator should be used in conjunction with the
enterprise_login_required decorator.
Usage::
@enterprise_login_required
@force_fresh_session()
def my_view(request, enterprise_uuid):
# Some functionality ...
OR
class MyView(View):
...
@method_decorator(enterprise_login_required)
@method_decorator(force_fresh_session)
def get(self, request, enterprise_uuid):
# Some functionality ...
"""
@wraps(view)
def wrapper(request, *args, **kwargs):
"""
Wrap the function.
"""
if not request.GET.get(FRESH_LOGIN_PARAMETER):
# The enterprise_login_required decorator promises to set the fresh login URL
# parameter for this URL when it was the agent that initiated the login process;
# if that parameter isn't set, we can safely assume that the session is "stale";
# that isn't necessarily an issue, though. Redirect the user to
# log out and then come back here - the enterprise_login_required decorator will
# then take effect prior to us arriving back | 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("User does not exist")
try:
| 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.enterprise_customer_user,
| 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.
"""
request = self.context['request']
enterprise_customer = instance.enterprise_customer
representation = super(EnterpriseCustomerCatalogDetailSerializer, self).to_representation(instance)
# Retrieve the EnterpriseCustomerCatalog search results from the discovery service.
paginated_content = instance.get_paginated_content(request.GET)
count = paginated_content['count']
search_results = paginated_content['results']
for item in search_results:
content_type = item['content_type']
marketing_url = item.get('marketing_url')
if marketing_url:
item['marketing_url'] = utils.update_query_parameters(
marketing_url, utils.get_enterprise_utm_context(enterprise_customer)
)
# Add the Enterprise enrollment URL to each content item returned from the discovery service.
if content_type == 'course':
item['enrollment_url'] = instance.get_course_enrollment_url(item['key'])
| 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 | 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)
| 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(
| 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_catalog = self.context['enterprise_customer_catalog']
updated_course['enrollment_url'] = enterprise_customer_catalog.get_course_enrollment_url(
updated_course['key']
)
| 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)
enterprise_customer_catalog = self.context['enterprise_customer_catalog']
| 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_customer_catalog = self.context['enterprise_customer_catalog']
updated_program['enrollment_url'] = enterprise_customer_catalog.get_program_enrollment_url(
updated_program['uuid']
)
| 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_messages['not_a_list'].format(
input_type=type(data).__name__
)
raise serializers.ValidationError({
api_settings.NON_FIELD_ERRORS_KEY: [message]
| 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 [
| 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 = validated_data.get('tpa_user_id')
user_email = validated_data.get('user_email')
course_run_id = validated_data.get('course_run_id')
course_mode = validated_data.get('course_mode')
cohort = validated_data.get('cohort')
email_students = validated_data.get('email_students')
is_active = validated_data.get('is_active')
enterprise_customer_user = lms_user or tpa_user or user_email
if isinstance(enterprise_customer_user, models.EnterpriseCustomerUser):
validated_data['enterprise_customer_user'] = enterprise_customer_user
try:
if is_active:
enterprise_customer_user.enroll(course_run_id, course_mode, cohort=cohort)
else:
enterprise_customer_user.unenroll(course_run_id)
except (CourseEnrollmentDowngradeError, CourseEnrollmentPermissionError, HttpClientError) as exc:
validated_data['detail'] = str(exc)
| 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 enterprise.
| 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('enterprise_customer')
try:
tpa_client = ThirdPartyAuthApiClient()
username = tpa_client.get_username_from_remote_id(
enterprise_customer.identity_provider, value
)
| 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('enterprise_customer')
try:
user = User.objects.get(email=value)
| 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.ValidationError(
'The course run id {course_run_id} is | 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 not lms_user_id and not tpa_user_id and not user_email:
| 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 containing pagination links.
"""
url = urlparse(request.build_absolute_uri())._replace(query=None).geturl()
next_page = None
previous_page = None
if data['next']:
next_page = "{base_url}?{query_parameters}".format(
base_url=url,
query_parameters=urlparse(data['next']).query,
)
next_page = next_page.rstrip('?')
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.