partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
AssertionBuilder.does_not_contain_value
Asserts that val is a dict and does not contain the given value or values.
assertpy/assertpy.py
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(): found.append(v) if found: self._err('Expected <%s> to not contain values %s, but did contain %s.' % (self.val, self._fmt_items(values), self._fmt_items(found))) return self
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(): found.append(v) if found: self._err('Expected <%s> to not contain values %s, but did contain %s.' % (self.val, self._fmt_items(values), self._fmt_items(found))) return self
[ "Asserts", "that", "val", "is", "a", "dict", "and", "does", "not", "contain", "the", "given", "value", "or", "values", "." ]
ActivisionGameScience/assertpy
python
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L801-L813
[ "def", "does_not_contain_value", "(", "self", ",", "*", "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", "(", ")", ":", "found", ".", "append", "(", "v", ")", "if", "found", ":", "self", ".", "_err", "(", "'Expected <%s> to not contain values %s, but did contain %s.'", "%", "(", "self", ".", "val", ",", "self", ".", "_fmt_items", "(", "values", ")", ",", "self", ".", "_fmt_items", "(", "found", ")", ")", ")", "return", "self" ]
08d799cdb01f9a25d3e20672efac991c7bc26d79
valid
AssertionBuilder.contains_entry
Asserts that val is a dict and contains the given entry or entries.
assertpy/assertpy.py
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: if type(e) is not dict: raise TypeError('given entry arg must be a dict') if len(e) != 1: raise ValueError('given entry args must contain exactly one key-value pair') k = next(iter(e)) if k not in self.val: missing.append(e) # bad key elif self.val[k] != e[k]: missing.append(e) # bad val if missing: self._err('Expected <%s> to contain entries %s, but did not contain %s.' % (self.val, self._fmt_items(entries), self._fmt_items(missing))) return self
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: if type(e) is not dict: raise TypeError('given entry arg must be a dict') if len(e) != 1: raise ValueError('given entry args must contain exactly one key-value pair') k = next(iter(e)) if k not in self.val: missing.append(e) # bad key elif self.val[k] != e[k]: missing.append(e) # bad val if missing: self._err('Expected <%s> to contain entries %s, but did not contain %s.' % (self.val, self._fmt_items(entries), self._fmt_items(missing))) return self
[ "Asserts", "that", "val", "is", "a", "dict", "and", "contains", "the", "given", "entry", "or", "entries", "." ]
ActivisionGameScience/assertpy
python
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L815-L834
[ "def", "contains_entry", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "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", ":", "if", "type", "(", "e", ")", "is", "not", "dict", ":", "raise", "TypeError", "(", "'given entry arg must be a dict'", ")", "if", "len", "(", "e", ")", "!=", "1", ":", "raise", "ValueError", "(", "'given entry args must contain exactly one key-value pair'", ")", "k", "=", "next", "(", "iter", "(", "e", ")", ")", "if", "k", "not", "in", "self", ".", "val", ":", "missing", ".", "append", "(", "e", ")", "# bad key", "elif", "self", ".", "val", "[", "k", "]", "!=", "e", "[", "k", "]", ":", "missing", ".", "append", "(", "e", ")", "# bad val", "if", "missing", ":", "self", ".", "_err", "(", "'Expected <%s> to contain entries %s, but did not contain %s.'", "%", "(", "self", ".", "val", ",", "self", ".", "_fmt_items", "(", "entries", ")", ",", "self", ".", "_fmt_items", "(", "missing", ")", ")", ")", "return", "self" ]
08d799cdb01f9a25d3e20672efac991c7bc26d79
valid
AssertionBuilder.is_before
Asserts that val is a date and is before other date.
assertpy/assertpy.py
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>' % type(other).__name__) if self.val >= other: self._err('Expected <%s> to be before <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'))) return self
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>' % type(other).__name__) if self.val >= other: self._err('Expected <%s> to be before <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'))) return self
[ "Asserts", "that", "val", "is", "a", "date", "and", "is", "before", "other", "date", "." ]
ActivisionGameScience/assertpy
python
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L856-L864
[ "def", "is_before", "(", "self", ",", "other", ")", ":", "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>'", "%", "type", "(", "other", ")", ".", "__name__", ")", "if", "self", ".", "val", ">=", "other", ":", "self", ".", "_err", "(", "'Expected <%s> to be before <%s>, but was not.'", "%", "(", "self", ".", "val", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", ",", "other", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", ")", ")", "return", "self" ]
08d799cdb01f9a25d3e20672efac991c7bc26d79
valid
AssertionBuilder.exists
Asserts that val is a path and that it exists.
assertpy/assertpy.py
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
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
[ "Asserts", "that", "val", "is", "a", "path", "and", "that", "it", "exists", "." ]
ActivisionGameScience/assertpy
python
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L904-L910
[ "def", "exists", "(", "self", ")", ":", "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" ]
08d799cdb01f9a25d3e20672efac991c7bc26d79
valid
AssertionBuilder.is_file
Asserts that val is an existing path to a file.
assertpy/assertpy.py
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
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
[ "Asserts", "that", "val", "is", "an", "existing", "path", "to", "a", "file", "." ]
ActivisionGameScience/assertpy
python
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L920-L925
[ "def", "is_file", "(", "self", ")", ":", "self", ".", "exists", "(", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "self", ".", "val", ")", ":", "self", ".", "_err", "(", "'Expected <%s> to be a file, but was not.'", "%", "self", ".", "val", ")", "return", "self" ]
08d799cdb01f9a25d3e20672efac991c7bc26d79
valid
AssertionBuilder.is_directory
Asserts that val is an existing path to a directory.
assertpy/assertpy.py
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
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
[ "Asserts", "that", "val", "is", "an", "existing", "path", "to", "a", "directory", "." ]
ActivisionGameScience/assertpy
python
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L927-L932
[ "def", "is_directory", "(", "self", ")", ":", "self", ".", "exists", "(", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "self", ".", "val", ")", ":", "self", ".", "_err", "(", "'Expected <%s> to be a directory, but was not.'", "%", "self", ".", "val", ")", "return", "self" ]
08d799cdb01f9a25d3e20672efac991c7bc26d79
valid
AssertionBuilder.is_named
Asserts that val is an existing path to a file and that file is named filename.
assertpy/assertpy.py
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)) if val_filename != filename: self._err('Expected filename <%s> to be equal to <%s>, but was not.' % (val_filename, filename)) return self
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)) if val_filename != filename: self._err('Expected filename <%s> to be equal to <%s>, but was not.' % (val_filename, filename)) return self
[ "Asserts", "that", "val", "is", "an", "existing", "path", "to", "a", "file", "and", "that", "file", "is", "named", "filename", "." ]
ActivisionGameScience/assertpy
python
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L934-L942
[ "def", "is_named", "(", "self", ",", "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", ")", ")", "if", "val_filename", "!=", "filename", ":", "self", ".", "_err", "(", "'Expected filename <%s> to be equal to <%s>, but was not.'", "%", "(", "val_filename", ",", "filename", ")", ")", "return", "self" ]
08d799cdb01f9a25d3e20672efac991c7bc26d79
valid
AssertionBuilder.is_child_of
Asserts that val is an existing path to a file and that file is a child of parent.
assertpy/assertpy.py
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) if not val_abspath.startswith(parent_abspath): self._err('Expected file <%s> to be a child of <%s>, but was not.' % (val_abspath, parent_abspath)) return self
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) if not val_abspath.startswith(parent_abspath): self._err('Expected file <%s> to be a child of <%s>, but was not.' % (val_abspath, parent_abspath)) return self
[ "Asserts", "that", "val", "is", "an", "existing", "path", "to", "a", "file", "and", "that", "file", "is", "a", "child", "of", "parent", "." ]
ActivisionGameScience/assertpy
python
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L944-L953
[ "def", "is_child_of", "(", "self", ",", "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", ")", "if", "not", "val_abspath", ".", "startswith", "(", "parent_abspath", ")", ":", "self", ".", "_err", "(", "'Expected file <%s> to be a child of <%s>, but was not.'", "%", "(", "val_abspath", ",", "parent_abspath", ")", ")", "return", "self" ]
08d799cdb01f9a25d3e20672efac991c7bc26d79
valid
AssertionBuilder.extracting
Asserts that val is collection, then extracts the named properties or named zero-arg methods into a list (or list of tuples if multiple names are given).
assertpy/assertpy.py
def extracting(self, *names, **kwargs): """Asserts that val is collection, then extracts the named properties or named zero-arg methods into a list (or list of tuples if multiple names are given).""" if not isinstance(self.val, Iterable): raise TypeError('val is not iterable') if isinstance(self.val, str_types): raise TypeError('val must not be string') if len(names) == 0: raise ValueError('one or more name args must be given') def _extract(x, name): if self._check_dict_like(x, check_values=False, return_as_bool=True): if name in x: return x[name] else: raise ValueError('item keys %s did not contain key <%s>' % (list(x.keys()), name)) elif isinstance(x, Iterable): self._check_iterable(x, name='item') return x[name] elif hasattr(x, name): attr = getattr(x, name) if callable(attr): try: return attr() except TypeError: raise ValueError('val method <%s()> exists, but is not zero-arg method' % name) else: return attr else: raise ValueError('val does not have property or zero-arg method <%s>' % name) def _filter(x): if 'filter' in kwargs: if isinstance(kwargs['filter'], str_types): return bool(_extract(x, kwargs['filter'])) elif self._check_dict_like(kwargs['filter'], check_values=False, return_as_bool=True): for k in kwargs['filter']: if isinstance(k, str_types): if _extract(x, k) != kwargs['filter'][k]: return False return True elif callable(kwargs['filter']): return kwargs['filter'](x) return False return True def _sort(x): if 'sort' in kwargs: if isinstance(kwargs['sort'], str_types): return _extract(x, kwargs['sort']) elif isinstance(kwargs['sort'], Iterable): items = [] for k in kwargs['sort']: if isinstance(k, str_types): items.append(_extract(x, k)) return tuple(items) elif callable(kwargs['sort']): return kwargs['sort'](x) return 0 extracted = [] for i in sorted(self.val, key=lambda x: _sort(x)): if _filter(i): items = [_extract(i, name) for name in names] extracted.append(tuple(items) if len(items) > 1 else items[0]) return AssertionBuilder(extracted, self.description, self.kind)
def extracting(self, *names, **kwargs): """Asserts that val is collection, then extracts the named properties or named zero-arg methods into a list (or list of tuples if multiple names are given).""" if not isinstance(self.val, Iterable): raise TypeError('val is not iterable') if isinstance(self.val, str_types): raise TypeError('val must not be string') if len(names) == 0: raise ValueError('one or more name args must be given') def _extract(x, name): if self._check_dict_like(x, check_values=False, return_as_bool=True): if name in x: return x[name] else: raise ValueError('item keys %s did not contain key <%s>' % (list(x.keys()), name)) elif isinstance(x, Iterable): self._check_iterable(x, name='item') return x[name] elif hasattr(x, name): attr = getattr(x, name) if callable(attr): try: return attr() except TypeError: raise ValueError('val method <%s()> exists, but is not zero-arg method' % name) else: return attr else: raise ValueError('val does not have property or zero-arg method <%s>' % name) def _filter(x): if 'filter' in kwargs: if isinstance(kwargs['filter'], str_types): return bool(_extract(x, kwargs['filter'])) elif self._check_dict_like(kwargs['filter'], check_values=False, return_as_bool=True): for k in kwargs['filter']: if isinstance(k, str_types): if _extract(x, k) != kwargs['filter'][k]: return False return True elif callable(kwargs['filter']): return kwargs['filter'](x) return False return True def _sort(x): if 'sort' in kwargs: if isinstance(kwargs['sort'], str_types): return _extract(x, kwargs['sort']) elif isinstance(kwargs['sort'], Iterable): items = [] for k in kwargs['sort']: if isinstance(k, str_types): items.append(_extract(x, k)) return tuple(items) elif callable(kwargs['sort']): return kwargs['sort'](x) return 0 extracted = [] for i in sorted(self.val, key=lambda x: _sort(x)): if _filter(i): items = [_extract(i, name) for name in names] extracted.append(tuple(items) if len(items) > 1 else items[0]) return AssertionBuilder(extracted, self.description, self.kind)
[ "Asserts", "that", "val", "is", "collection", "then", "extracts", "the", "named", "properties", "or", "named", "zero", "-", "arg", "methods", "into", "a", "list", "(", "or", "list", "of", "tuples", "if", "multiple", "names", "are", "given", ")", "." ]
ActivisionGameScience/assertpy
python
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L956-L1020
[ "def", "extracting", "(", "self", ",", "*", "names", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "self", ".", "val", ",", "Iterable", ")", ":", "raise", "TypeError", "(", "'val is not iterable'", ")", "if", "isinstance", "(", "self", ".", "val", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'val must not be string'", ")", "if", "len", "(", "names", ")", "==", "0", ":", "raise", "ValueError", "(", "'one or more name args must be given'", ")", "def", "_extract", "(", "x", ",", "name", ")", ":", "if", "self", ".", "_check_dict_like", "(", "x", ",", "check_values", "=", "False", ",", "return_as_bool", "=", "True", ")", ":", "if", "name", "in", "x", ":", "return", "x", "[", "name", "]", "else", ":", "raise", "ValueError", "(", "'item keys %s did not contain key <%s>'", "%", "(", "list", "(", "x", ".", "keys", "(", ")", ")", ",", "name", ")", ")", "elif", "isinstance", "(", "x", ",", "Iterable", ")", ":", "self", ".", "_check_iterable", "(", "x", ",", "name", "=", "'item'", ")", "return", "x", "[", "name", "]", "elif", "hasattr", "(", "x", ",", "name", ")", ":", "attr", "=", "getattr", "(", "x", ",", "name", ")", "if", "callable", "(", "attr", ")", ":", "try", ":", "return", "attr", "(", ")", "except", "TypeError", ":", "raise", "ValueError", "(", "'val method <%s()> exists, but is not zero-arg method'", "%", "name", ")", "else", ":", "return", "attr", "else", ":", "raise", "ValueError", "(", "'val does not have property or zero-arg method <%s>'", "%", "name", ")", "def", "_filter", "(", "x", ")", ":", "if", "'filter'", "in", "kwargs", ":", "if", "isinstance", "(", "kwargs", "[", "'filter'", "]", ",", "str_types", ")", ":", "return", "bool", "(", "_extract", "(", "x", ",", "kwargs", "[", "'filter'", "]", ")", ")", "elif", "self", ".", "_check_dict_like", "(", "kwargs", "[", "'filter'", "]", ",", "check_values", "=", "False", ",", "return_as_bool", "=", "True", ")", ":", "for", "k", "in", "kwargs", "[", "'filter'", "]", ":", "if", "isinstance", "(", "k", ",", "str_types", ")", ":", "if", "_extract", "(", "x", ",", "k", ")", "!=", "kwargs", "[", "'filter'", "]", "[", "k", "]", ":", "return", "False", "return", "True", "elif", "callable", "(", "kwargs", "[", "'filter'", "]", ")", ":", "return", "kwargs", "[", "'filter'", "]", "(", "x", ")", "return", "False", "return", "True", "def", "_sort", "(", "x", ")", ":", "if", "'sort'", "in", "kwargs", ":", "if", "isinstance", "(", "kwargs", "[", "'sort'", "]", ",", "str_types", ")", ":", "return", "_extract", "(", "x", ",", "kwargs", "[", "'sort'", "]", ")", "elif", "isinstance", "(", "kwargs", "[", "'sort'", "]", ",", "Iterable", ")", ":", "items", "=", "[", "]", "for", "k", "in", "kwargs", "[", "'sort'", "]", ":", "if", "isinstance", "(", "k", ",", "str_types", ")", ":", "items", ".", "append", "(", "_extract", "(", "x", ",", "k", ")", ")", "return", "tuple", "(", "items", ")", "elif", "callable", "(", "kwargs", "[", "'sort'", "]", ")", ":", "return", "kwargs", "[", "'sort'", "]", "(", "x", ")", "return", "0", "extracted", "=", "[", "]", "for", "i", "in", "sorted", "(", "self", ".", "val", ",", "key", "=", "lambda", "x", ":", "_sort", "(", "x", ")", ")", ":", "if", "_filter", "(", "i", ")", ":", "items", "=", "[", "_extract", "(", "i", ",", "name", ")", "for", "name", "in", "names", "]", "extracted", ".", "append", "(", "tuple", "(", "items", ")", "if", "len", "(", "items", ")", ">", "1", "else", "items", "[", "0", "]", ")", "return", "AssertionBuilder", "(", "extracted", ",", "self", ".", "description", ",", "self", ".", "kind", ")" ]
08d799cdb01f9a25d3e20672efac991c7bc26d79
valid
AssertionBuilder.raises
Asserts that val is callable and that when called raises the given error.
assertpy/assertpy.py
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 AssertionBuilder(self.val, self.description, self.kind, ex)
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 AssertionBuilder(self.val, self.description, self.kind, ex)
[ "Asserts", "that", "val", "is", "callable", "and", "that", "when", "called", "raises", "the", "given", "error", "." ]
ActivisionGameScience/assertpy
python
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L1067-L1073
[ "def", "raises", "(", "self", ",", "ex", ")", ":", "if", "not", "callable", "(", "self", ".", "val", ")", ":", "raise", "TypeError", "(", "'val must be callable'", ")", "if", "not", "issubclass", "(", "ex", ",", "BaseException", ")", ":", "raise", "TypeError", "(", "'given arg must be exception'", ")", "return", "AssertionBuilder", "(", "self", ".", "val", ",", "self", ".", "description", ",", "self", ".", "kind", ",", "ex", ")" ]
08d799cdb01f9a25d3e20672efac991c7bc26d79
valid
AssertionBuilder.when_called_with
Asserts the val callable when invoked with the given args and kwargs raises the expected exception.
assertpy/assertpy.py
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 return AssertionBuilder(str(e), self.description, self.kind) else: # got exception, but wrong type, so raise self._err('Expected <%s> to raise <%s> when called with (%s), but raised <%s>.' % ( self.val.__name__, self.expected.__name__, self._fmt_args_kwargs(*some_args, **some_kwargs), type(e).__name__)) # didn't fail as expected, so raise self._err('Expected <%s> to raise <%s> when called with (%s).' % ( self.val.__name__, self.expected.__name__, self._fmt_args_kwargs(*some_args, **some_kwargs)))
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 return AssertionBuilder(str(e), self.description, self.kind) else: # got exception, but wrong type, so raise self._err('Expected <%s> to raise <%s> when called with (%s), but raised <%s>.' % ( self.val.__name__, self.expected.__name__, self._fmt_args_kwargs(*some_args, **some_kwargs), type(e).__name__)) # didn't fail as expected, so raise self._err('Expected <%s> to raise <%s> when called with (%s).' % ( self.val.__name__, self.expected.__name__, self._fmt_args_kwargs(*some_args, **some_kwargs)))
[ "Asserts", "the", "val", "callable", "when", "invoked", "with", "the", "given", "args", "and", "kwargs", "raises", "the", "expected", "exception", "." ]
ActivisionGameScience/assertpy
python
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L1075-L1097
[ "def", "when_called_with", "(", "self", ",", "*", "some_args", ",", "*", "*", "some_kwargs", ")", ":", "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", "return", "AssertionBuilder", "(", "str", "(", "e", ")", ",", "self", ".", "description", ",", "self", ".", "kind", ")", "else", ":", "# got exception, but wrong type, so raise", "self", ".", "_err", "(", "'Expected <%s> to raise <%s> when called with (%s), but raised <%s>.'", "%", "(", "self", ".", "val", ".", "__name__", ",", "self", ".", "expected", ".", "__name__", ",", "self", ".", "_fmt_args_kwargs", "(", "*", "some_args", ",", "*", "*", "some_kwargs", ")", ",", "type", "(", "e", ")", ".", "__name__", ")", ")", "# didn't fail as expected, so raise", "self", ".", "_err", "(", "'Expected <%s> to raise <%s> when called with (%s).'", "%", "(", "self", ".", "val", ".", "__name__", ",", "self", ".", "expected", ".", "__name__", ",", "self", ".", "_fmt_args_kwargs", "(", "*", "some_args", ",", "*", "*", "some_kwargs", ")", ")", ")" ]
08d799cdb01f9a25d3e20672efac991c7bc26d79
valid
AssertionBuilder._err
Helper to raise an AssertionError, and optionally prepend custom description.
assertpy/assertpy.py
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': global _soft_err _soft_err.append(out) return self else: raise AssertionError(out)
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': global _soft_err _soft_err.append(out) return self else: raise AssertionError(out)
[ "Helper", "to", "raise", "an", "AssertionError", "and", "optionally", "prepend", "custom", "description", "." ]
ActivisionGameScience/assertpy
python
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L1100-L1111
[ "def", "_err", "(", "self", ",", "msg", ")", ":", "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'", ":", "global", "_soft_err", "_soft_err", ".", "append", "(", "out", ")", "return", "self", "else", ":", "raise", "AssertionError", "(", "out", ")" ]
08d799cdb01f9a25d3e20672efac991c7bc26d79
valid
AssertionBuilder._fmt_args_kwargs
Helper to convert the given args and kwargs into a string.
assertpy/assertpy.py
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())]]) if some_args and some_kwargs: return out_args + ', ' + out_kwargs elif some_args: return out_args elif some_kwargs: return out_kwargs else: return ''
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())]]) if some_args and some_kwargs: return out_args + ', ' + out_kwargs elif some_args: return out_args elif some_kwargs: return out_kwargs else: return ''
[ "Helper", "to", "convert", "the", "given", "args", "and", "kwargs", "into", "a", "string", "." ]
ActivisionGameScience/assertpy
python
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L1121-L1136
[ "def", "_fmt_args_kwargs", "(", "self", ",", "*", "some_args", ",", "*", "*", "some_kwargs", ")", ":", "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", "(", ")", ")", "]", "]", ")", "if", "some_args", "and", "some_kwargs", ":", "return", "out_args", "+", "', '", "+", "out_kwargs", "elif", "some_args", ":", "return", "out_args", "elif", "some_kwargs", ":", "return", "out_kwargs", "else", ":", "return", "''" ]
08d799cdb01f9a25d3e20672efac991c7bc26d79
valid
generate_words
Transform list of files to list of words, removing new line character and replace name entity '<NE>...</NE>' and abbreviation '<AB>...</AB>' symbol
deepcut/train.py
def generate_words(files): """ Transform list of files to list of words, removing new line character and replace name entity '<NE>...</NE>' and abbreviation '<AB>...</AB>' symbol """ repls = {'<NE>' : '','</NE>' : '','<AB>': '','</AB>': ''} words_all = [] for i, file in enumerate(files): lines = open(file, 'r') for line in lines: line = reduce(lambda a, kv: a.replace(*kv), repls.items(), line) words = [word for word in line.split("|") if word is not '\n'] words_all.extend(words) return words_all
def generate_words(files): """ Transform list of files to list of words, removing new line character and replace name entity '<NE>...</NE>' and abbreviation '<AB>...</AB>' symbol """ repls = {'<NE>' : '','</NE>' : '','<AB>': '','</AB>': ''} words_all = [] for i, file in enumerate(files): lines = open(file, 'r') for line in lines: line = reduce(lambda a, kv: a.replace(*kv), repls.items(), line) words = [word for word in line.split("|") if word is not '\n'] words_all.extend(words) return words_all
[ "Transform", "list", "of", "files", "to", "list", "of", "words", "removing", "new", "line", "character", "and", "replace", "name", "entity", "<NE", ">", "...", "<", "/", "NE", ">", "and", "abbreviation", "<AB", ">", "...", "<", "/", "AB", ">", "symbol" ]
rkcosmos/deepcut
python
https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/train.py#L20-L36
[ "def", "generate_words", "(", "files", ")", ":", "repls", "=", "{", "'<NE>'", ":", "''", ",", "'</NE>'", ":", "''", ",", "'<AB>'", ":", "''", ",", "'</AB>'", ":", "''", "}", "words_all", "=", "[", "]", "for", "i", ",", "file", "in", "enumerate", "(", "files", ")", ":", "lines", "=", "open", "(", "file", ",", "'r'", ")", "for", "line", "in", "lines", ":", "line", "=", "reduce", "(", "lambda", "a", ",", "kv", ":", "a", ".", "replace", "(", "*", "kv", ")", ",", "repls", ".", "items", "(", ")", ",", "line", ")", "words", "=", "[", "word", "for", "word", "in", "line", ".", "split", "(", "\"|\"", ")", "if", "word", "is", "not", "'\\n'", "]", "words_all", ".", "extend", "(", "words", ")", "return", "words_all" ]
9a2729071d01972af805acede85d7aa9e7a6da30
valid
create_char_dataframe
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}]
deepcut/train.py
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, 'type': CHAR_TYPE_FLATTEN.get(char, 'o'), 'target': True}) else: char_dict.append({'char': char, 'type': CHAR_TYPE_FLATTEN.get(char, 'o'), 'target': False}) return pd.DataFrame(char_dict)
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, 'type': CHAR_TYPE_FLATTEN.get(char, 'o'), 'target': True}) else: char_dict.append({'char': char, 'type': CHAR_TYPE_FLATTEN.get(char, 'o'), 'target': False}) return pd.DataFrame(char_dict)
[ "Give", "list", "of", "input", "tokenized", "words", "create", "dataframe", "of", "characters", "where", "first", "character", "of", "the", "word", "is", "tagged", "as", "1", "otherwise", "0" ]
rkcosmos/deepcut
python
https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/train.py#L39-L62
[ "def", "create_char_dataframe", "(", "words", ")", ":", "char_dict", "=", "[", "]", "for", "word", "in", "words", ":", "for", "i", ",", "char", "in", "enumerate", "(", "word", ")", ":", "if", "i", "==", "0", ":", "char_dict", ".", "append", "(", "{", "'char'", ":", "char", ",", "'type'", ":", "CHAR_TYPE_FLATTEN", ".", "get", "(", "char", ",", "'o'", ")", ",", "'target'", ":", "True", "}", ")", "else", ":", "char_dict", ".", "append", "(", "{", "'char'", ":", "char", ",", "'type'", ":", "CHAR_TYPE_FLATTEN", ".", "get", "(", "char", ",", "'o'", ")", ",", "'target'", ":", "False", "}", ")", "return", "pd", ".", "DataFrame", "(", "char_dict", ")" ]
9a2729071d01972af805acede85d7aa9e7a6da30
valid
generate_best_dataset
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
deepcut/train.py
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) if create_val: files_train, files_val = train_test_split(files_train, random_state=0, test_size=0.1) val_words = generate_words(files_val) val_df = create_char_dataframe(val_words) val_df.to_csv(os.path.join(output_path, 'val', 'df_best_{}_val.csv'.format(article_type)), index=False) train_words = generate_words(files_train) test_words = generate_words(files_test) train_df = create_char_dataframe(train_words) test_df = create_char_dataframe(test_words) train_df.to_csv(os.path.join(output_path, 'train', 'df_best_{}_train.csv'.format(article_type)), index=False) test_df.to_csv(os.path.join(output_path, 'test', 'df_best_{}_test.csv'.format(article_type)), index=False) print("Save {} to CSV file".format(article_type))
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) if create_val: files_train, files_val = train_test_split(files_train, random_state=0, test_size=0.1) val_words = generate_words(files_val) val_df = create_char_dataframe(val_words) val_df.to_csv(os.path.join(output_path, 'val', 'df_best_{}_val.csv'.format(article_type)), index=False) train_words = generate_words(files_train) test_words = generate_words(files_test) train_df = create_char_dataframe(train_words) test_df = create_char_dataframe(test_words) train_df.to_csv(os.path.join(output_path, 'train', 'df_best_{}_train.csv'.format(article_type)), index=False) test_df.to_csv(os.path.join(output_path, 'test', 'df_best_{}_test.csv'.format(article_type)), index=False) print("Save {} to CSV file".format(article_type))
[ "Generate", "CSV", "file", "for", "training", "and", "testing", "data" ]
rkcosmos/deepcut
python
https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/train.py#L65-L104
[ "def", "generate_best_dataset", "(", "best_path", ",", "output_path", "=", "'cleaned_data'", ",", "create_val", "=", "False", ")", ":", "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", ")", "if", "create_val", ":", "files_train", ",", "files_val", "=", "train_test_split", "(", "files_train", ",", "random_state", "=", "0", ",", "test_size", "=", "0.1", ")", "val_words", "=", "generate_words", "(", "files_val", ")", "val_df", "=", "create_char_dataframe", "(", "val_words", ")", "val_df", ".", "to_csv", "(", "os", ".", "path", ".", "join", "(", "output_path", ",", "'val'", ",", "'df_best_{}_val.csv'", ".", "format", "(", "article_type", ")", ")", ",", "index", "=", "False", ")", "train_words", "=", "generate_words", "(", "files_train", ")", "test_words", "=", "generate_words", "(", "files_test", ")", "train_df", "=", "create_char_dataframe", "(", "train_words", ")", "test_df", "=", "create_char_dataframe", "(", "test_words", ")", "train_df", ".", "to_csv", "(", "os", ".", "path", ".", "join", "(", "output_path", ",", "'train'", ",", "'df_best_{}_train.csv'", ".", "format", "(", "article_type", ")", ")", ",", "index", "=", "False", ")", "test_df", ".", "to_csv", "(", "os", ".", "path", ".", "join", "(", "output_path", ",", "'test'", ",", "'df_best_{}_test.csv'", ".", "format", "(", "article_type", ")", ")", ",", "index", "=", "False", ")", "print", "(", "\"Save {} to CSV file\"", ".", "format", "(", "article_type", ")", ")" ]
9a2729071d01972af805acede85d7aa9e7a6da30
valid
prepare_feature
Transform processed path into feature matrix and output array Input ===== best_processed_path: str, path to processed BEST dataset option: str, 'train' or 'test'
deepcut/train.py
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)))) df = pd.concat(df) df = pd.concat((df_pad, df, df_pad)) # pad with empty string feature df['char'] = df['char'].map(lambda x: CHARS_MAP.get(x, 80)) df['type'] = df['type'].map(lambda x: CHAR_TYPES_MAP.get(x, 4)) df_pad = create_n_gram_df(df, n_pad=n_pad) char_row = ['char' + str(i + 1) for i in range(n_pad_2)] + \ ['char-' + str(i + 1) for i in range(n_pad_2)] + ['char'] type_row = ['type' + str(i + 1) for i in range(n_pad_2)] + \ ['type-' + str(i + 1) for i in range(n_pad_2)] + ['type'] x_char = df_pad[char_row].as_matrix() x_type = df_pad[type_row].as_matrix() y = df_pad['target'].astype(int).as_matrix() return x_char, x_type, y
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)))) df = pd.concat(df) df = pd.concat((df_pad, df, df_pad)) # pad with empty string feature df['char'] = df['char'].map(lambda x: CHARS_MAP.get(x, 80)) df['type'] = df['type'].map(lambda x: CHAR_TYPES_MAP.get(x, 4)) df_pad = create_n_gram_df(df, n_pad=n_pad) char_row = ['char' + str(i + 1) for i in range(n_pad_2)] + \ ['char-' + str(i + 1) for i in range(n_pad_2)] + ['char'] type_row = ['type' + str(i + 1) for i in range(n_pad_2)] + \ ['type-' + str(i + 1) for i in range(n_pad_2)] + ['type'] x_char = df_pad[char_row].as_matrix() x_type = df_pad[type_row].as_matrix() y = df_pad['target'].astype(int).as_matrix() return x_char, x_type, y
[ "Transform", "processed", "path", "into", "feature", "matrix", "and", "output", "array" ]
rkcosmos/deepcut
python
https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/train.py#L107-L142
[ "def", "prepare_feature", "(", "best_processed_path", ",", "option", "=", "'train'", ")", ":", "# 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", ")", ")", ")", ")", "df", "=", "pd", ".", "concat", "(", "df", ")", "df", "=", "pd", ".", "concat", "(", "(", "df_pad", ",", "df", ",", "df_pad", ")", ")", "# pad with empty string feature", "df", "[", "'char'", "]", "=", "df", "[", "'char'", "]", ".", "map", "(", "lambda", "x", ":", "CHARS_MAP", ".", "get", "(", "x", ",", "80", ")", ")", "df", "[", "'type'", "]", "=", "df", "[", "'type'", "]", ".", "map", "(", "lambda", "x", ":", "CHAR_TYPES_MAP", ".", "get", "(", "x", ",", "4", ")", ")", "df_pad", "=", "create_n_gram_df", "(", "df", ",", "n_pad", "=", "n_pad", ")", "char_row", "=", "[", "'char'", "+", "str", "(", "i", "+", "1", ")", "for", "i", "in", "range", "(", "n_pad_2", ")", "]", "+", "[", "'char-'", "+", "str", "(", "i", "+", "1", ")", "for", "i", "in", "range", "(", "n_pad_2", ")", "]", "+", "[", "'char'", "]", "type_row", "=", "[", "'type'", "+", "str", "(", "i", "+", "1", ")", "for", "i", "in", "range", "(", "n_pad_2", ")", "]", "+", "[", "'type-'", "+", "str", "(", "i", "+", "1", ")", "for", "i", "in", "range", "(", "n_pad_2", ")", "]", "+", "[", "'type'", "]", "x_char", "=", "df_pad", "[", "char_row", "]", ".", "as_matrix", "(", ")", "x_type", "=", "df_pad", "[", "type_row", "]", ".", "as_matrix", "(", ")", "y", "=", "df_pad", "[", "'target'", "]", ".", "astype", "(", "int", ")", ".", "as_matrix", "(", ")", "return", "x_char", ",", "x_type", ",", "y" ]
9a2729071d01972af805acede85d7aa9e7a6da30
valid
train_model
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
deepcut/train.py
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 ) ] # train model model = get_convo_nn2() train_params = [(10, 256), (3, 512), (3, 2048), (3, 4096), (3, 8192)] for (epochs, batch_size) in train_params: print("train with {} epochs and {} batch size".format(epochs, batch_size)) if validation_set: model.fit([x_train_char, x_train_type], y_train, epochs=epochs, batch_size=batch_size, verbose=verbose, callbacks=callbacks_list, validation_data=([x_val_char, x_val_type], y_val)) else: model.fit([x_train_char, x_train_type], y_train, epochs=epochs, batch_size=batch_size, verbose=verbose, callbacks=callbacks_list) return model
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 ) ] # train model model = get_convo_nn2() train_params = [(10, 256), (3, 512), (3, 2048), (3, 4096), (3, 8192)] for (epochs, batch_size) in train_params: print("train with {} epochs and {} batch size".format(epochs, batch_size)) if validation_set: model.fit([x_train_char, x_train_type], y_train, epochs=epochs, batch_size=batch_size, verbose=verbose, callbacks=callbacks_list, validation_data=([x_val_char, x_val_type], y_val)) else: model.fit([x_train_char, x_train_type], y_train, epochs=epochs, batch_size=batch_size, verbose=verbose, callbacks=callbacks_list) return model
[ "Given", "path", "to", "processed", "BEST", "dataset", "train", "CNN", "model", "for", "words", "beginning", "alongside", "with", "character", "label", "encoder", "and", "character", "type", "label", "encoder" ]
rkcosmos/deepcut
python
https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/train.py#L145-L201
[ "def", "train_model", "(", "best_processed_path", ",", "weight_path", "=", "'../weight/model_weight.h5'", ",", "verbose", "=", "2", ")", ":", "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", ")", "]", "# train model", "model", "=", "get_convo_nn2", "(", ")", "train_params", "=", "[", "(", "10", ",", "256", ")", ",", "(", "3", ",", "512", ")", ",", "(", "3", ",", "2048", ")", ",", "(", "3", ",", "4096", ")", ",", "(", "3", ",", "8192", ")", "]", "for", "(", "epochs", ",", "batch_size", ")", "in", "train_params", ":", "print", "(", "\"train with {} epochs and {} batch size\"", ".", "format", "(", "epochs", ",", "batch_size", ")", ")", "if", "validation_set", ":", "model", ".", "fit", "(", "[", "x_train_char", ",", "x_train_type", "]", ",", "y_train", ",", "epochs", "=", "epochs", ",", "batch_size", "=", "batch_size", ",", "verbose", "=", "verbose", ",", "callbacks", "=", "callbacks_list", ",", "validation_data", "=", "(", "[", "x_val_char", ",", "x_val_type", "]", ",", "y_val", ")", ")", "else", ":", "model", ".", "fit", "(", "[", "x_train_char", ",", "x_train_type", "]", ",", "y_train", ",", "epochs", "=", "epochs", ",", "batch_size", "=", "batch_size", ",", "verbose", "=", "verbose", ",", "callbacks", "=", "callbacks_list", ")", "return", "model" ]
9a2729071d01972af805acede85d7aa9e7a6da30
valid
evaluate
Evaluate model on splitted 10 percent testing set
deepcut/train.py
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) f1score = f1_score(y_test, y_predict) precision = precision_score(y_test, y_predict) recall = recall_score(y_test, y_predict) return f1score, precision, recall
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) f1score = f1_score(y_test, y_predict) precision = precision_score(y_test, y_predict) recall = recall_score(y_test, y_predict) return f1score, precision, recall
[ "Evaluate", "model", "on", "splitted", "10", "percent", "testing", "set" ]
rkcosmos/deepcut
python
https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/train.py#L204-L217
[ "def", "evaluate", "(", "best_processed_path", ",", "model", ")", ":", "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", ")", "f1score", "=", "f1_score", "(", "y_test", ",", "y_predict", ")", "precision", "=", "precision_score", "(", "y_test", ",", "y_predict", ")", "recall", "=", "recall_score", "(", "y_test", ",", "y_predict", ")", "return", "f1score", ",", "precision", ",", "recall" ]
9a2729071d01972af805acede85d7aa9e7a6da30
valid
tokenize
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 ====== tokens: list, list of tokenized words Example ======= >> deepcut.tokenize('ตัดคำได้ดีมาก') >> ['ตัดคำ','ได้','ดี','มาก']
deepcut/deepcut.py
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 ====== tokens: list, list of tokenized words Example ======= >> deepcut.tokenize('ตัดคำได้ดีมาก') >> ['ตัดคำ','ได้','ดี','มาก'] """ global TOKENIZER if not TOKENIZER: TOKENIZER = DeepcutTokenizer() return TOKENIZER.tokenize(text, custom_dict=custom_dict)
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 ====== tokens: list, list of tokenized words Example ======= >> deepcut.tokenize('ตัดคำได้ดีมาก') >> ['ตัดคำ','ได้','ดี','มาก'] """ global TOKENIZER if not TOKENIZER: TOKENIZER = DeepcutTokenizer() return TOKENIZER.tokenize(text, custom_dict=custom_dict)
[ "Tokenize", "given", "Thai", "text", "string" ]
rkcosmos/deepcut
python
https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/deepcut.py#L23-L48
[ "def", "tokenize", "(", "text", ",", "custom_dict", "=", "None", ")", ":", "global", "TOKENIZER", "if", "not", "TOKENIZER", ":", "TOKENIZER", "=", "DeepcutTokenizer", "(", ")", "return", "TOKENIZER", ".", "tokenize", "(", "text", ",", "custom_dict", "=", "custom_dict", ")" ]
9a2729071d01972af805acede85d7aa9e7a6da30
valid
_document_frequency
Count the number of non-zero values for each feature in sparse X.
deepcut/deepcut.py
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)
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)
[ "Count", "the", "number", "of", "non", "-", "zero", "values", "for", "each", "feature", "in", "sparse", "X", "." ]
rkcosmos/deepcut
python
https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/deepcut.py#L70-L76
[ "def", "_document_frequency", "(", "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", ")" ]
9a2729071d01972af805acede85d7aa9e7a6da30
valid
_check_stop_list
Check stop words list ref: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L87-L95
deepcut/deepcut.py
def _check_stop_list(stop): """ Check stop words list ref: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L87-L95 """ if stop == "thai": return THAI_STOP_WORDS elif isinstance(stop, six.string_types): raise ValueError("not a built-in stop list: %s" % stop) elif stop is None: return None # assume it's a collection return frozenset(stop)
def _check_stop_list(stop): """ Check stop words list ref: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L87-L95 """ if stop == "thai": return THAI_STOP_WORDS elif isinstance(stop, six.string_types): raise ValueError("not a built-in stop list: %s" % stop) elif stop is None: return None # assume it's a collection return frozenset(stop)
[ "Check", "stop", "words", "list", "ref", ":", "https", ":", "//", "github", ".", "com", "/", "scikit", "-", "learn", "/", "scikit", "-", "learn", "/", "blob", "/", "master", "/", "sklearn", "/", "feature_extraction", "/", "text", ".", "py#L87", "-", "L95" ]
rkcosmos/deepcut
python
https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/deepcut.py#L79-L91
[ "def", "_check_stop_list", "(", "stop", ")", ":", "if", "stop", "==", "\"thai\"", ":", "return", "THAI_STOP_WORDS", "elif", "isinstance", "(", "stop", ",", "six", ".", "string_types", ")", ":", "raise", "ValueError", "(", "\"not a built-in stop list: %s\"", "%", "stop", ")", "elif", "stop", "is", "None", ":", "return", "None", "# assume it's a collection", "return", "frozenset", "(", "stop", ")" ]
9a2729071d01972af805acede85d7aa9e7a6da30
valid
DeepcutTokenizer._word_ngrams
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
deepcut/deepcut.py
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 = [] n_original_tokens = len(original_tokens) # bind method outside of loop to reduce overhead tokens_append = tokens.append space_join = " ".join for n in range(min_n, min(max_n + 1, n_original_tokens + 1)): for i in range(n_original_tokens - n + 1): tokens_append(space_join(original_tokens[i: i + n])) return tokens
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 = [] n_original_tokens = len(original_tokens) # bind method outside of loop to reduce overhead tokens_append = tokens.append space_join = " ".join for n in range(min_n, min(max_n + 1, n_original_tokens + 1)): for i in range(n_original_tokens - n + 1): tokens_append(space_join(original_tokens[i: i + n])) return tokens
[ "Turn", "tokens", "into", "a", "tokens", "of", "n", "-", "grams" ]
rkcosmos/deepcut
python
https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/deepcut.py#L146-L179
[ "def", "_word_ngrams", "(", "self", ",", "tokens", ")", ":", "# 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", "=", "[", "]", "n_original_tokens", "=", "len", "(", "original_tokens", ")", "# bind method outside of loop to reduce overhead", "tokens_append", "=", "tokens", ".", "append", "space_join", "=", "\" \"", ".", "join", "for", "n", "in", "range", "(", "min_n", ",", "min", "(", "max_n", "+", "1", ",", "n_original_tokens", "+", "1", ")", ")", ":", "for", "i", "in", "range", "(", "n_original_tokens", "-", "n", "+", "1", ")", ":", "tokens_append", "(", "space_join", "(", "original_tokens", "[", "i", ":", "i", "+", "n", "]", ")", ")", "return", "tokens" ]
9a2729071d01972af805acede85d7aa9e7a6da30
valid
DeepcutTokenizer.fit_tranform
Transform given list of raw_documents to document-term matrix in sparse CSR format (see scipy)
deepcut/deepcut.py
def fit_tranform(self, raw_documents): """ Transform given list of raw_documents to document-term matrix in sparse CSR format (see scipy) """ X = self.transform(raw_documents, new_document=True) return X
def fit_tranform(self, raw_documents): """ Transform given list of raw_documents to document-term matrix in sparse CSR format (see scipy) """ X = self.transform(raw_documents, new_document=True) return X
[ "Transform", "given", "list", "of", "raw_documents", "to", "document", "-", "term", "matrix", "in", "sparse", "CSR", "format", "(", "see", "scipy", ")" ]
rkcosmos/deepcut
python
https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/deepcut.py#L273-L279
[ "def", "fit_tranform", "(", "self", ",", "raw_documents", ")", ":", "X", "=", "self", ".", "transform", "(", "raw_documents", ",", "new_document", "=", "True", ")", "return", "X" ]
9a2729071d01972af805acede85d7aa9e7a6da30
valid
create_feature_array
Create feature array of character and surrounding characters
deepcut/utils.py
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 char_list] char_type = [CHAR_TYPES_MAP.get(CHAR_TYPE_FLATTEN.get(c, 'o'), 4) for c in char_list] x_char.append(char_map) x_type.append(char_type) x_char = np.array(x_char).astype(float) x_type = np.array(x_type).astype(float) return x_char, x_type
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 char_list] char_type = [CHAR_TYPES_MAP.get(CHAR_TYPE_FLATTEN.get(c, 'o'), 4) for c in char_list] x_char.append(char_map) x_type.append(char_type) x_char = np.array(x_char).astype(float) x_type = np.array(x_type).astype(float) return x_char, x_type
[ "Create", "feature", "array", "of", "character", "and", "surrounding", "characters" ]
rkcosmos/deepcut
python
https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/utils.py#L55-L74
[ "def", "create_feature_array", "(", "text", ",", "n_pad", "=", "21", ")", ":", "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", "char_list", "]", "char_type", "=", "[", "CHAR_TYPES_MAP", ".", "get", "(", "CHAR_TYPE_FLATTEN", ".", "get", "(", "c", ",", "'o'", ")", ",", "4", ")", "for", "c", "in", "char_list", "]", "x_char", ".", "append", "(", "char_map", ")", "x_type", ".", "append", "(", "char_type", ")", "x_char", "=", "np", ".", "array", "(", "x_char", ")", ".", "astype", "(", "float", ")", "x_type", "=", "np", ".", "array", "(", "x_type", ")", ".", "astype", "(", "float", ")", "return", "x_char", ",", "x_type" ]
9a2729071d01972af805acede85d7aa9e7a6da30
valid
create_n_gram_df
Given input dataframe, create feature dataframe of shifted characters
deepcut/utils.py
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['char{}'.format(i+1)] = df['char'].shift(-i - 1) df['type{}'.format(i+1)] = df['type'].shift(-i - 1) return df[n_pad_2: -n_pad_2]
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['char{}'.format(i+1)] = df['char'].shift(-i - 1) df['type{}'.format(i+1)] = df['type'].shift(-i - 1) return df[n_pad_2: -n_pad_2]
[ "Given", "input", "dataframe", "create", "feature", "dataframe", "of", "shifted", "characters" ]
rkcosmos/deepcut
python
https://github.com/rkcosmos/deepcut/blob/9a2729071d01972af805acede85d7aa9e7a6da30/deepcut/utils.py#L77-L87
[ "def", "create_n_gram_df", "(", "df", ",", "n_pad", ")", ":", "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", "[", "'char{}'", ".", "format", "(", "i", "+", "1", ")", "]", "=", "df", "[", "'char'", "]", ".", "shift", "(", "-", "i", "-", "1", ")", "df", "[", "'type{}'", ".", "format", "(", "i", "+", "1", ")", "]", "=", "df", "[", "'type'", "]", ".", "shift", "(", "-", "i", "-", "1", ")", "return", "df", "[", "n_pad_2", ":", "-", "n_pad_2", "]" ]
9a2729071d01972af805acede85d7aa9e7a6da30
valid
Command._fetch_course_enrollment_data
Return enterprise customer UUID/user_id/course_run_id triples which represent CourseEnrollment records which do not have a matching EnterpriseCourseEnrollment record. The query used below looks for CourseEnrollment records that are associated with enterprise learners where the enrollment data is after the creation of the link between the learner and the enterprise. It also excludes learners with edx.org email addresses in order to filter out test users.
enterprise/management/commands/create_enterprise_course_enrollments.py
def _fetch_course_enrollment_data(self, enterprise_customer_uuid): """ Return enterprise customer UUID/user_id/course_run_id triples which represent CourseEnrollment records which do not have a matching EnterpriseCourseEnrollment record. The query used below looks for CourseEnrollment records that are associated with enterprise learners where the enrollment data is after the creation of the link between the learner and the enterprise. It also excludes learners with edx.org email addresses in order to filter out test users. """ query = ''' SELECT au.id as user_id, ecu.enterprise_customer_id as enterprise_customer_uuid, sce.course_id as course_run_id FROM student_courseenrollment sce JOIN auth_user au ON au.id = sce.user_id JOIN enterprise_enterprisecustomeruser ecu ON ecu.user_id = au.id LEFT JOIN enterprise_enterprisecourseenrollment ece ON ece.enterprise_customer_user_id = ecu.id AND ece.course_id = sce.course_id WHERE ece.id IS NULL AND ecu.created <= sce.created AND au.email NOT LIKE '%@edx.org' {enterprise_customer_filter} ORDER BY sce.created; ''' with connection.cursor() as cursor: if enterprise_customer_uuid: cursor.execute( query.format(enterprise_customer_filter='AND ecu.enterprise_customer_id = %s'), [enterprise_customer_uuid] ) else: cursor.execute( query.format(enterprise_customer_filter='') ) return self._dictfetchall(cursor)
def _fetch_course_enrollment_data(self, enterprise_customer_uuid): """ Return enterprise customer UUID/user_id/course_run_id triples which represent CourseEnrollment records which do not have a matching EnterpriseCourseEnrollment record. The query used below looks for CourseEnrollment records that are associated with enterprise learners where the enrollment data is after the creation of the link between the learner and the enterprise. It also excludes learners with edx.org email addresses in order to filter out test users. """ query = ''' SELECT au.id as user_id, ecu.enterprise_customer_id as enterprise_customer_uuid, sce.course_id as course_run_id FROM student_courseenrollment sce JOIN auth_user au ON au.id = sce.user_id JOIN enterprise_enterprisecustomeruser ecu ON ecu.user_id = au.id LEFT JOIN enterprise_enterprisecourseenrollment ece ON ece.enterprise_customer_user_id = ecu.id AND ece.course_id = sce.course_id WHERE ece.id IS NULL AND ecu.created <= sce.created AND au.email NOT LIKE '%@edx.org' {enterprise_customer_filter} ORDER BY sce.created; ''' with connection.cursor() as cursor: if enterprise_customer_uuid: cursor.execute( query.format(enterprise_customer_filter='AND ecu.enterprise_customer_id = %s'), [enterprise_customer_uuid] ) else: cursor.execute( query.format(enterprise_customer_filter='') ) return self._dictfetchall(cursor)
[ "Return", "enterprise", "customer", "UUID", "/", "user_id", "/", "course_run_id", "triples", "which", "represent", "CourseEnrollment", "records", "which", "do", "not", "have", "a", "matching", "EnterpriseCourseEnrollment", "record", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/management/commands/create_enterprise_course_enrollments.py#L77-L119
[ "def", "_fetch_course_enrollment_data", "(", "self", ",", "enterprise_customer_uuid", ")", ":", "query", "=", "'''\n SELECT\n au.id as user_id,\n ecu.enterprise_customer_id as enterprise_customer_uuid,\n sce.course_id as course_run_id\n FROM student_courseenrollment sce\n JOIN auth_user au\n ON au.id = sce.user_id\n JOIN enterprise_enterprisecustomeruser ecu\n ON ecu.user_id = au.id\n LEFT JOIN enterprise_enterprisecourseenrollment ece\n ON ece.enterprise_customer_user_id = ecu.id\n AND ece.course_id = sce.course_id\n WHERE\n ece.id IS NULL\n AND ecu.created <= sce.created\n AND au.email NOT LIKE '%@edx.org'\n {enterprise_customer_filter}\n ORDER BY sce.created;\n '''", "with", "connection", ".", "cursor", "(", ")", "as", "cursor", ":", "if", "enterprise_customer_uuid", ":", "cursor", ".", "execute", "(", "query", ".", "format", "(", "enterprise_customer_filter", "=", "'AND ecu.enterprise_customer_id = %s'", ")", ",", "[", "enterprise_customer_uuid", "]", ")", "else", ":", "cursor", ".", "execute", "(", "query", ".", "format", "(", "enterprise_customer_filter", "=", "''", ")", ")", "return", "self", ".", "_dictfetchall", "(", "cursor", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
Command._dictfetchall
Return all rows from a cursor as a dict.
enterprise/management/commands/create_enterprise_course_enrollments.py
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() ]
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() ]
[ "Return", "all", "rows", "from", "a", "cursor", "as", "a", "dict", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/management/commands/create_enterprise_course_enrollments.py#L121-L127
[ "def", "_dictfetchall", "(", "self", ",", "cursor", ")", ":", "columns", "=", "[", "col", "[", "0", "]", "for", "col", "in", "cursor", ".", "description", "]", "return", "[", "dict", "(", "zip", "(", "columns", ",", "row", ")", ")", "for", "row", "in", "cursor", ".", "fetchall", "(", ")", "]" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
parse_lms_api_datetime
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
enterprise/api_client/lms.py
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 else: try: date_time = datetime.datetime.strptime(datetime_string, datetime_format) except ValueError: date_time = datetime.datetime.strptime(datetime_string, LMS_API_DATETIME_FORMAT_WITHOUT_TIMEZONE) # If the datetime format didn't include a timezone, then set to UTC. # Note that if we're using the default LMS_API_DATETIME_FORMAT, it ends in 'Z', # which denotes UTC for ISO-8661. if date_time.tzinfo is None: date_time = date_time.replace(tzinfo=timezone.utc) return date_time
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 else: try: date_time = datetime.datetime.strptime(datetime_string, datetime_format) except ValueError: date_time = datetime.datetime.strptime(datetime_string, LMS_API_DATETIME_FORMAT_WITHOUT_TIMEZONE) # If the datetime format didn't include a timezone, then set to UTC. # Note that if we're using the default LMS_API_DATETIME_FORMAT, it ends in 'Z', # which denotes UTC for ISO-8661. if date_time.tzinfo is None: date_time = date_time.replace(tzinfo=timezone.utc) return date_time
[ "Parse", "a", "received", "datetime", "into", "a", "timezone", "-", "aware", "Python", "datetime", "object", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L483-L505
[ "def", "parse_lms_api_datetime", "(", "datetime_string", ",", "datetime_format", "=", "LMS_API_DATETIME_FORMAT", ")", ":", "if", "isinstance", "(", "datetime_string", ",", "datetime", ".", "datetime", ")", ":", "date_time", "=", "datetime_string", "else", ":", "try", ":", "date_time", "=", "datetime", ".", "datetime", ".", "strptime", "(", "datetime_string", ",", "datetime_format", ")", "except", "ValueError", ":", "date_time", "=", "datetime", ".", "datetime", ".", "strptime", "(", "datetime_string", ",", "LMS_API_DATETIME_FORMAT_WITHOUT_TIMEZONE", ")", "# If the datetime format didn't include a timezone, then set to UTC.", "# Note that if we're using the default LMS_API_DATETIME_FORMAT, it ends in 'Z',", "# which denotes UTC for ISO-8661.", "if", "date_time", ".", "tzinfo", "is", "None", ":", "date_time", "=", "date_time", ".", "replace", "(", "tzinfo", "=", "timezone", ".", "utc", ")", "return", "date_time" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
JwtLmsApiClient.connect
Connect to the REST API, authenticating with a JWT for the current user.
enterprise/api_client/lms.py
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) self.client = EdxRestApiClient( self.API_BASE_URL, append_slash=self.APPEND_SLASH, jwt=jwt, ) self.expires_at = now + self.expires_in
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) self.client = EdxRestApiClient( self.API_BASE_URL, append_slash=self.APPEND_SLASH, jwt=jwt, ) self.expires_at = now + self.expires_in
[ "Connect", "to", "the", "REST", "API", "authenticating", "with", "a", "JWT", "for", "the", "current", "user", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L78-L90
[ "def", "connect", "(", "self", ")", ":", "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", ")", "self", ".", "client", "=", "EdxRestApiClient", "(", "self", ".", "API_BASE_URL", ",", "append_slash", "=", "self", ".", "APPEND_SLASH", ",", "jwt", "=", "jwt", ",", ")", "self", ".", "expires_at", "=", "now", "+", "self", ".", "expires_in" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
JwtLmsApiClient.refresh_token
Use this method decorator to ensure the JWT token is refreshed when needed.
enterprise/api_client/lms.py
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. """ if self.token_expired(): self.connect() return func(self, *args, **kwargs) return inner
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. """ if self.token_expired(): self.connect() return func(self, *args, **kwargs) return inner
[ "Use", "this", "method", "decorator", "to", "ensure", "the", "JWT", "token", "is", "refreshed", "when", "needed", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L99-L111
[ "def", "refresh_token", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "inner", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Before calling the wrapped function, we check if the JWT token is expired, and if so, re-connect.\n \"\"\"", "if", "self", ".", "token_expired", "(", ")", ":", "self", ".", "connect", "(", ")", "return", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "inner" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EmbargoApiClient.redirect_if_blocked
Return redirect to embargo error page if the given user is blocked.
enterprise/api_client/lms.py
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), user=user, ip_address=ip_address, url=url ) if redirect_url: return redirect_url
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), user=user, ip_address=ip_address, url=url ) if redirect_url: return redirect_url
[ "Return", "redirect", "to", "embargo", "error", "page", "if", "the", "given", "user", "is", "blocked", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L120-L132
[ "def", "redirect_if_blocked", "(", "course_run_ids", ",", "user", "=", "None", ",", "ip_address", "=", "None", ",", "url", "=", "None", ")", ":", "for", "course_run_id", "in", "course_run_ids", ":", "redirect_url", "=", "embargo_api", ".", "redirect_if_blocked", "(", "CourseKey", ".", "from_string", "(", "course_run_id", ")", ",", "user", "=", "user", ",", "ip_address", "=", "ip_address", ",", "url", "=", "url", ")", "if", "redirect_url", ":", "return", "redirect_url" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnrollmentApiClient.get_course_details
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.)
enterprise/api_client/lms.py
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: return self.client.course(course_id).get() except (SlumberBaseException, ConnectionError, Timeout) as exc: LOGGER.exception( 'Failed to retrieve course enrollment details for course [%s] due to: [%s]', course_id, str(exc) ) return {}
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: return self.client.course(course_id).get() except (SlumberBaseException, ConnectionError, Timeout) as exc: LOGGER.exception( 'Failed to retrieve course enrollment details for course [%s] due to: [%s]', course_id, str(exc) ) return {}
[ "Query", "the", "Enrollment", "API", "for", "the", "course", "details", "of", "the", "given", "course_id", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L142-L159
[ "def", "get_course_details", "(", "self", ",", "course_id", ")", ":", "try", ":", "return", "self", ".", "client", ".", "course", "(", "course_id", ")", ".", "get", "(", ")", "except", "(", "SlumberBaseException", ",", "ConnectionError", ",", "Timeout", ")", "as", "exc", ":", "LOGGER", ".", "exception", "(", "'Failed to retrieve course enrollment details for course [%s] due to: [%s]'", ",", "course_id", ",", "str", "(", "exc", ")", ")", "return", "{", "}" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnrollmentApiClient._sort_course_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.
enterprise/api_client/lms.py
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 sorting_slugs_size = len(sorting_slugs) if mode['slug'] in sorting_slugs: return sorting_slugs_size - sorting_slugs.index(mode['slug']) return 0 # Sort slug weights in descending order return sorted(modes, key=slug_weight, reverse=True)
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 sorting_slugs_size = len(sorting_slugs) if mode['slug'] in sorting_slugs: return sorting_slugs_size - sorting_slugs.index(mode['slug']) return 0 # Sort slug weights in descending order return sorted(modes, key=slug_weight, reverse=True)
[ "Sort", "the", "course", "mode", "dictionaries", "by", "slug", "according", "to", "the", "COURSE_MODE_SORT_ORDER", "constant", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L161-L181
[ "def", "_sort_course_modes", "(", "self", ",", "modes", ")", ":", "def", "slug_weight", "(", "mode", ")", ":", "\"\"\"\n Assign a weight to the course mode dictionary based on the position of its slug in the sorting list.\n \"\"\"", "sorting_slugs", "=", "COURSE_MODE_SORT_ORDER", "sorting_slugs_size", "=", "len", "(", "sorting_slugs", ")", "if", "mode", "[", "'slug'", "]", "in", "sorting_slugs", ":", "return", "sorting_slugs_size", "-", "sorting_slugs", ".", "index", "(", "mode", "[", "'slug'", "]", ")", "return", "0", "# Sort slug weights in descending order", "return", "sorted", "(", "modes", ",", "key", "=", "slug_weight", ",", "reverse", "=", "True", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnrollmentApiClient.get_course_modes
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.
enterprise/api_client/lms.py
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. """ details = self.get_course_details(course_id) modes = details.get('course_modes', []) return self._sort_course_modes([mode for mode in modes if mode['slug'] not in EXCLUDED_COURSE_MODES])
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. """ details = self.get_course_details(course_id) modes = details.get('course_modes', []) return self._sort_course_modes([mode for mode in modes if mode['slug'] not in EXCLUDED_COURSE_MODES])
[ "Query", "the", "Enrollment", "API", "for", "the", "specific", "course", "modes", "that", "are", "available", "for", "the", "given", "course_id", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L183-L196
[ "def", "get_course_modes", "(", "self", ",", "course_id", ")", ":", "details", "=", "self", ".", "get_course_details", "(", "course_id", ")", "modes", "=", "details", ".", "get", "(", "'course_modes'", ",", "[", "]", ")", "return", "self", ".", "_sort_course_modes", "(", "[", "mode", "for", "mode", "in", "modes", "if", "mode", "[", "'slug'", "]", "not", "in", "EXCLUDED_COURSE_MODES", "]", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnrollmentApiClient.has_course_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 given mode avaialble for enrollment.
enterprise/api_client/lms.py
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 given mode avaialble for enrollment. """ course_modes = self.get_course_modes(course_run_id) return any(course_mode for course_mode in course_modes if course_mode['slug'] == mode)
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 given mode avaialble for enrollment. """ course_modes = self.get_course_modes(course_run_id) return any(course_mode for course_mode in course_modes if course_mode['slug'] == mode)
[ "Query", "the", "Enrollment", "API", "to", "see", "whether", "a", "course", "run", "has", "a", "given", "course", "mode", "available", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L198-L210
[ "def", "has_course_mode", "(", "self", ",", "course_run_id", ",", "mode", ")", ":", "course_modes", "=", "self", ".", "get_course_modes", "(", "course_run_id", ")", "return", "any", "(", "course_mode", "for", "course_mode", "in", "course_modes", "if", "course_mode", "[", "'slug'", "]", "==", "mode", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnrollmentApiClient.enroll_user_in_course
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 the enrollment, including course details, mode, username, etc.
enterprise/api_client/lms.py
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 the enrollment, including course details, mode, username, etc. """ return self.client.enrollment.post( { 'user': username, 'course_details': {'course_id': course_id}, 'mode': mode, 'cohort': cohort, } )
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 the enrollment, including course details, mode, username, etc. """ return self.client.enrollment.post( { 'user': username, 'course_details': {'course_id': course_id}, 'mode': mode, 'cohort': cohort, } )
[ "Call", "the", "enrollment", "API", "to", "enroll", "the", "user", "in", "the", "course", "specified", "by", "course_id", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L212-L233
[ "def", "enroll_user_in_course", "(", "self", ",", "username", ",", "course_id", ",", "mode", ",", "cohort", "=", "None", ")", ":", "return", "self", ".", "client", ".", "enrollment", ".", "post", "(", "{", "'user'", ":", "username", ",", "'course_details'", ":", "{", "'course_id'", ":", "course_id", "}", ",", "'mode'", ":", "mode", ",", "'cohort'", ":", "cohort", ",", "}", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnrollmentApiClient.unenroll_user_from_course
Call the enrollment API to unenroll 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 Returns: bool: Whether the unenrollment succeeded
enterprise/api_client/lms.py
def unenroll_user_from_course(self, username, course_id): """ Call the enrollment API to unenroll 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 Returns: bool: Whether the unenrollment succeeded """ enrollment = self.get_course_enrollment(username, course_id) if enrollment and enrollment['is_active']: response = self.client.enrollment.post({ 'user': username, 'course_details': {'course_id': course_id}, 'is_active': False, 'mode': enrollment['mode'] }) return not response['is_active'] return False
def unenroll_user_from_course(self, username, course_id): """ Call the enrollment API to unenroll 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 Returns: bool: Whether the unenrollment succeeded """ enrollment = self.get_course_enrollment(username, course_id) if enrollment and enrollment['is_active']: response = self.client.enrollment.post({ 'user': username, 'course_details': {'course_id': course_id}, 'is_active': False, 'mode': enrollment['mode'] }) return not response['is_active'] return False
[ "Call", "the", "enrollment", "API", "to", "unenroll", "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", "Returns", ":", "bool", ":", "Whether", "the", "unenrollment", "succeeded" ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L235-L254
[ "def", "unenroll_user_from_course", "(", "self", ",", "username", ",", "course_id", ")", ":", "enrollment", "=", "self", ".", "get_course_enrollment", "(", "username", ",", "course_id", ")", "if", "enrollment", "and", "enrollment", "[", "'is_active'", "]", ":", "response", "=", "self", ".", "client", ".", "enrollment", ".", "post", "(", "{", "'user'", ":", "username", ",", "'course_details'", ":", "{", "'course_id'", ":", "course_id", "}", ",", "'is_active'", ":", "False", ",", "'mode'", ":", "enrollment", "[", "'mode'", "]", "}", ")", "return", "not", "response", "[", "'is_active'", "]", "return", "False" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnrollmentApiClient.get_course_enrollment
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.
enterprise/api_client/lms.py
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 LOGGER.error( 'Course enrollment details not found for invalid username or course; username=[%s], course=[%s]', username, course_id ) return None # This enrollment data endpoint returns an empty string if the username and course_id is valid, but there's # no matching enrollment found if not result: LOGGER.info('Failed to find course enrollment details for user [%s] and course [%s]', username, course_id) return None return result
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 LOGGER.error( 'Course enrollment details not found for invalid username or course; username=[%s], course=[%s]', username, course_id ) return None # This enrollment data endpoint returns an empty string if the username and course_id is valid, but there's # no matching enrollment found if not result: LOGGER.info('Failed to find course enrollment details for user [%s] and course [%s]', username, course_id) return None return result
[ "Query", "the", "enrollment", "API", "to", "get", "information", "about", "a", "single", "course", "enrollment", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L256-L288
[ "def", "get_course_enrollment", "(", "self", ",", "username", ",", "course_id", ")", ":", "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", "LOGGER", ".", "error", "(", "'Course enrollment details not found for invalid username or course; username=[%s], course=[%s]'", ",", "username", ",", "course_id", ")", "return", "None", "# This enrollment data endpoint returns an empty string if the username and course_id is valid, but there's", "# no matching enrollment found", "if", "not", "result", ":", "LOGGER", ".", "info", "(", "'Failed to find course enrollment details for user [%s] and course [%s]'", ",", "username", ",", "course_id", ")", "return", "None", "return", "result" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnrollmentApiClient.is_enrolled
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: bool: Indicating whether the user is enrolled in the course run. Returns False under any errors.
enterprise/api_client/lms.py
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: bool: Indicating whether the user is enrolled in the course run. Returns False under any errors. """ enrollment = self.get_course_enrollment(username, course_run_id) return enrollment is not None and enrollment.get('is_active', False)
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: bool: Indicating whether the user is enrolled in the course run. Returns False under any errors. """ enrollment = self.get_course_enrollment(username, course_run_id) return enrollment is not None and enrollment.get('is_active', False)
[ "Query", "the", "enrollment", "API", "and", "determine", "if", "a", "learner", "is", "enrolled", "in", "a", "course", "run", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L290-L303
[ "def", "is_enrolled", "(", "self", ",", "username", ",", "course_run_id", ")", ":", "enrollment", "=", "self", ".", "get_course_enrollment", "(", "username", ",", "course_run_id", ")", "return", "enrollment", "is", "not", "None", "and", "enrollment", ".", "get", "(", "'is_active'", ",", "False", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
ThirdPartyAuthApiClient._get_results
Calls the third party auth api endpoint to get the mapping between usernames and remote ids.
enterprise/api_client/lms.py
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( provider=identity_provider, querystring_param=param_name, id=param_value ) ) results = [] for row in results: if row.get(param_name) == param_value: return row.get(result_field_name) return None
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( provider=identity_provider, querystring_param=param_name, id=param_value ) ) results = [] for row in results: if row.get(param_name) == param_value: return row.get(result_field_name) return None
[ "Calls", "the", "third", "party", "auth", "api", "endpoint", "to", "get", "the", "mapping", "between", "usernames", "and", "remote", "ids", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L377-L398
[ "def", "_get_results", "(", "self", ",", "identity_provider", ",", "param_name", ",", "param_value", ",", "result_field_name", ")", ":", "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", "(", "provider", "=", "identity_provider", ",", "querystring_param", "=", "param_name", ",", "id", "=", "param_value", ")", ")", "results", "=", "[", "]", "for", "row", "in", "results", ":", "if", "row", ".", "get", "(", "param_name", ")", "==", "param_value", ":", "return", "row", ".", "get", "(", "result_field_name", ")", "return", "None" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
GradesApiClient.get_course_grade
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 * ``letter_grade``: A letter grade as defined in grading_policy (e.g. 'A' 'B' 'C' for 6.002x) or None
enterprise/api_client/lms.py
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 * ``letter_grade``: A letter grade as defined in grading_policy (e.g. 'A' 'B' 'C' for 6.002x) or None """ results = self.client.courses(course_id).get(username=username) for row in results: if row.get('username') == username: return row raise HttpNotFoundError('No grade record found for course={}, username={}'.format(course_id, username))
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 * ``letter_grade``: A letter grade as defined in grading_policy (e.g. 'A' 'B' 'C' for 6.002x) or None """ results = self.client.courses(course_id).get(username=username) for row in results: if row.get('username') == username: return row raise HttpNotFoundError('No grade record found for course={}, username={}'.format(course_id, username))
[ "Retrieve", "the", "grade", "for", "the", "given", "username", "for", "the", "given", "course_id", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L412-L440
[ "def", "get_course_grade", "(", "self", ",", "course_id", ",", "username", ")", ":", "results", "=", "self", ".", "client", ".", "courses", "(", "course_id", ")", ".", "get", "(", "username", "=", "username", ")", "for", "row", "in", "results", ":", "if", "row", ".", "get", "(", "'username'", ")", "==", "username", ":", "return", "row", "raise", "HttpNotFoundError", "(", "'No grade record found for course={}, username={}'", ".", "format", "(", "course_id", ",", "username", ")", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CertificatesApiClient.get_course_certificate
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). * ``status``: A string representation of the certificate status. * ``is_passing``: True if the certificate has a passing status, False if not. * ``download_url``: A string representation of the certificate url. * ``grade``: A string representation of a float for the user's course grade.
enterprise/api_client/lms.py
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). * ``status``: A string representation of the certificate status. * ``is_passing``: True if the certificate has a passing status, False if not. * ``download_url``: A string representation of the certificate url. * ``grade``: A string representation of a float for the user's course grade. """ return self.client.certificates(username).courses(course_id).get()
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). * ``status``: A string representation of the certificate status. * ``is_passing``: True if the certificate has a passing status, False if not. * ``download_url``: A string representation of the certificate url. * ``grade``: A string representation of a float for the user's course grade. """ return self.client.certificates(username).courses(course_id).get()
[ "Retrieve", "the", "certificate", "for", "the", "given", "username", "for", "the", "given", "course_id", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/lms.py#L454-L480
[ "def", "get_course_certificate", "(", "self", ",", "course_id", ",", "username", ")", ":", "return", "self", ".", "client", ".", "certificates", "(", "username", ")", ".", "courses", "(", "course_id", ")", ".", "get", "(", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
course_discovery_api_client
Return a Course Discovery API client setup with authentication for the specified user.
enterprise/api_client/discovery.py
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 Open edX environment.") ) jwt = JwtBuilder.create_jwt_for_user(user) return EdxRestApiClient(catalog_url, jwt=jwt)
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 Open edX environment.") ) jwt = JwtBuilder.create_jwt_for_user(user) return EdxRestApiClient(catalog_url, jwt=jwt)
[ "Return", "a", "Course", "Discovery", "API", "client", "setup", "with", "authentication", "for", "the", "specified", "user", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L45-L56
[ "def", "course_discovery_api_client", "(", "user", ",", "catalog_url", ")", ":", "if", "JwtBuilder", "is", "None", ":", "raise", "NotConnectedToOpenEdX", "(", "_", "(", "\"To get a Catalog API client, this package must be \"", "\"installed in an Open edX environment.\"", ")", ")", "jwt", "=", "JwtBuilder", ".", "create_jwt_for_user", "(", "user", ")", "return", "EdxRestApiClient", "(", "catalog_url", ",", "jwt", "=", "jwt", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CourseCatalogApiClient.traverse_pagination
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.
enterprise/api_client/discovery.py
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. """ results = response.get('results', []) page = 1 while response.get('next'): page += 1 response = endpoint().post(content_filter_query, **dict(query_params, page=page)) results += response.get('results', []) return results
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. """ results = response.get('results', []) page = 1 while response.get('next'): page += 1 response = endpoint().post(content_filter_query, **dict(query_params, page=page)) results += response.get('results', []) return results
[ "Traverse", "a", "paginated", "API", "response", "and", "extracts", "and", "concatenates", "results", "returned", "by", "API", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L102-L123
[ "def", "traverse_pagination", "(", "response", ",", "endpoint", ",", "content_filter_query", ",", "query_params", ")", ":", "results", "=", "response", ".", "get", "(", "'results'", ",", "[", "]", ")", "page", "=", "1", "while", "response", ".", "get", "(", "'next'", ")", ":", "page", "+=", "1", "response", "=", "endpoint", "(", ")", ".", "post", "(", "content_filter_query", ",", "*", "*", "dict", "(", "query_params", ",", "page", "=", "page", ")", ")", "results", "+=", "response", ".", "get", "(", "'results'", ",", "[", "]", ")", "return", "results" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CourseCatalogApiClient.get_catalog_results
Return results from the discovery service's search/all endpoint. Arguments: content_filter_query (dict): query parameters used to filter catalog results. query_params (dict): query parameters used to paginate results. traverse_pagination (bool): True to return all results, False to return the paginated response. Defaults to False. Returns: dict: Paginated response or all the records.
enterprise/api_client/discovery.py
def get_catalog_results(self, content_filter_query, query_params=None, traverse_pagination=False): """ Return results from the discovery service's search/all endpoint. Arguments: content_filter_query (dict): query parameters used to filter catalog results. query_params (dict): query parameters used to paginate results. traverse_pagination (bool): True to return all results, False to return the paginated response. Defaults to False. Returns: dict: Paginated response or all the records. """ query_params = query_params or {} try: endpoint = getattr(self.client, self.SEARCH_ALL_ENDPOINT) response = endpoint().post(data=content_filter_query, **query_params) if traverse_pagination: response['results'] = self.traverse_pagination(response, endpoint, content_filter_query, query_params) response['next'] = response['previous'] = None except Exception as ex: # pylint: disable=broad-except LOGGER.exception( 'Attempted to call course-discovery search/all/ endpoint with the following parameters: ' 'content_filter_query: %s, query_params: %s, traverse_pagination: %s. ' 'Failed to retrieve data from the catalog API. content -- [%s]', content_filter_query, query_params, traverse_pagination, getattr(ex, 'content', '') ) # We need to bubble up failures when we encounter them instead of masking them! raise ex return response
def get_catalog_results(self, content_filter_query, query_params=None, traverse_pagination=False): """ Return results from the discovery service's search/all endpoint. Arguments: content_filter_query (dict): query parameters used to filter catalog results. query_params (dict): query parameters used to paginate results. traverse_pagination (bool): True to return all results, False to return the paginated response. Defaults to False. Returns: dict: Paginated response or all the records. """ query_params = query_params or {} try: endpoint = getattr(self.client, self.SEARCH_ALL_ENDPOINT) response = endpoint().post(data=content_filter_query, **query_params) if traverse_pagination: response['results'] = self.traverse_pagination(response, endpoint, content_filter_query, query_params) response['next'] = response['previous'] = None except Exception as ex: # pylint: disable=broad-except LOGGER.exception( 'Attempted to call course-discovery search/all/ endpoint with the following parameters: ' 'content_filter_query: %s, query_params: %s, traverse_pagination: %s. ' 'Failed to retrieve data from the catalog API. content -- [%s]', content_filter_query, query_params, traverse_pagination, getattr(ex, 'content', '') ) # We need to bubble up failures when we encounter them instead of masking them! raise ex return response
[ "Return", "results", "from", "the", "discovery", "service", "s", "search", "/", "all", "endpoint", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L125-L159
[ "def", "get_catalog_results", "(", "self", ",", "content_filter_query", ",", "query_params", "=", "None", ",", "traverse_pagination", "=", "False", ")", ":", "query_params", "=", "query_params", "or", "{", "}", "try", ":", "endpoint", "=", "getattr", "(", "self", ".", "client", ",", "self", ".", "SEARCH_ALL_ENDPOINT", ")", "response", "=", "endpoint", "(", ")", ".", "post", "(", "data", "=", "content_filter_query", ",", "*", "*", "query_params", ")", "if", "traverse_pagination", ":", "response", "[", "'results'", "]", "=", "self", ".", "traverse_pagination", "(", "response", ",", "endpoint", ",", "content_filter_query", ",", "query_params", ")", "response", "[", "'next'", "]", "=", "response", "[", "'previous'", "]", "=", "None", "except", "Exception", "as", "ex", ":", "# pylint: disable=broad-except", "LOGGER", ".", "exception", "(", "'Attempted to call course-discovery search/all/ endpoint with the following parameters: '", "'content_filter_query: %s, query_params: %s, traverse_pagination: %s. '", "'Failed to retrieve data from the catalog API. content -- [%s]'", ",", "content_filter_query", ",", "query_params", ",", "traverse_pagination", ",", "getattr", "(", "ex", ",", "'content'", ",", "''", ")", ")", "# We need to bubble up failures when we encounter them instead of masking them!", "raise", "ex", "return", "response" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CourseCatalogApiClient.get_catalog
Return specified course catalog. Returns: dict: catalog details if it is available for the user.
enterprise/api_client/discovery.py
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 )
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 )
[ "Return", "specified", "course", "catalog", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L174-L186
[ "def", "get_catalog", "(", "self", ",", "catalog_id", ")", ":", "return", "self", ".", "_load_data", "(", "self", ".", "CATALOGS_ENDPOINT", ",", "default", "=", "[", "]", ",", "resource_id", "=", "catalog_id", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CourseCatalogApiClient.get_paginated_catalog_courses
Return paginated response for all catalog courses. Returns: dict: API response with links to next and previous pages.
enterprise/api_client/discovery.py
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.format(catalog_id), default=[], querystring=querystring, traverse_pagination=False, many=False, )
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.format(catalog_id), default=[], querystring=querystring, traverse_pagination=False, many=False, )
[ "Return", "paginated", "response", "for", "all", "catalog", "courses", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L188-L202
[ "def", "get_paginated_catalog_courses", "(", "self", ",", "catalog_id", ",", "querystring", "=", "None", ")", ":", "return", "self", ".", "_load_data", "(", "self", ".", "CATALOGS_COURSES_ENDPOINT", ".", "format", "(", "catalog_id", ")", ",", "default", "=", "[", "]", ",", "querystring", "=", "querystring", ",", "traverse_pagination", "=", "False", ",", "many", "=", "False", ",", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CourseCatalogApiClient.get_paginated_catalogs
Return a paginated list of course catalogs, including name and ID. Returns: dict: Paginated response containing catalogs available for the user.
enterprise/api_client/discovery.py
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, default=[], querystring=querystring, traverse_pagination=False, many=False )
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, default=[], querystring=querystring, traverse_pagination=False, many=False )
[ "Return", "a", "paginated", "list", "of", "course", "catalogs", "including", "name", "and", "ID", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L204-L218
[ "def", "get_paginated_catalogs", "(", "self", ",", "querystring", "=", "None", ")", ":", "return", "self", ".", "_load_data", "(", "self", ".", "CATALOGS_ENDPOINT", ",", "default", "=", "[", "]", ",", "querystring", "=", "querystring", ",", "traverse_pagination", "=", "False", ",", "many", "=", "False", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CourseCatalogApiClient.get_catalog_courses
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
enterprise/api_client/discovery.py
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( self.CATALOGS_COURSES_ENDPOINT.format(catalog_id), default=[] )
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( self.CATALOGS_COURSES_ENDPOINT.format(catalog_id), default=[] )
[ "Return", "the", "courses", "included", "in", "a", "single", "course", "catalog", "by", "ID", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L220-L234
[ "def", "get_catalog_courses", "(", "self", ",", "catalog_id", ")", ":", "return", "self", ".", "_load_data", "(", "self", ".", "CATALOGS_COURSES_ENDPOINT", ".", "format", "(", "catalog_id", ")", ",", "default", "=", "[", "]", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CourseCatalogApiClient.get_course_and_course_run
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.
enterprise/api_client/discovery.py
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: # Find the specified course run. course_run = None course_runs = [course_run for course_run in course['course_runs'] if course_run['key'] == course_run_id] if course_runs: course_run = course_runs[0] return course, course_run
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: # Find the specified course run. course_run = None course_runs = [course_run for course_run in course['course_runs'] if course_run['key'] == course_run_id] if course_runs: course_run = course_runs[0] return course, course_run
[ "Return", "the", "course", "and", "course", "run", "metadata", "for", "the", "given", "course", "run", "ID", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L236-L259
[ "def", "get_course_and_course_run", "(", "self", ",", "course_run_id", ")", ":", "# 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", ":", "# Find the specified course run.", "course_run", "=", "None", "course_runs", "=", "[", "course_run", "for", "course_run", "in", "course", "[", "'course_runs'", "]", "if", "course_run", "[", "'key'", "]", "==", "course_run_id", "]", "if", "course_runs", ":", "course_run", "=", "course_runs", "[", "0", "]", "return", "course", ",", "course_run" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CourseCatalogApiClient.get_course_details
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.
enterprise/api_client/discovery.py
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._load_data( self.COURSES_ENDPOINT, resource_id=course_id, many=False )
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._load_data( self.COURSES_ENDPOINT, resource_id=course_id, many=False )
[ "Return", "the", "details", "of", "a", "single", "course", "by", "id", "-", "not", "a", "course", "run", "id", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L261-L276
[ "def", "get_course_details", "(", "self", ",", "course_id", ")", ":", "return", "self", ".", "_load_data", "(", "self", ".", "COURSES_ENDPOINT", ",", "resource_id", "=", "course_id", ",", "many", "=", "False", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CourseCatalogApiClient.get_program_by_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
enterprise/api_client/discovery.py
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 for program in all_programs if program.get('title') == program_title] if len(matching_programs) > 1: raise MultipleProgramMatchError(len(matching_programs)) elif len(matching_programs) == 1: return matching_programs[0] else: return None
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 for program in all_programs if program.get('title') == program_title] if len(matching_programs) > 1: raise MultipleProgramMatchError(len(matching_programs)) elif len(matching_programs) == 1: return matching_programs[0] else: return None
[ "Return", "single", "program", "by", "name", "or", "None", "if", "not", "found", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L294-L312
[ "def", "get_program_by_title", "(", "self", ",", "program_title", ")", ":", "all_programs", "=", "self", ".", "_load_data", "(", "self", ".", "PROGRAMS_ENDPOINT", ",", "default", "=", "[", "]", ")", "matching_programs", "=", "[", "program", "for", "program", "in", "all_programs", "if", "program", ".", "get", "(", "'title'", ")", "==", "program_title", "]", "if", "len", "(", "matching_programs", ")", ">", "1", ":", "raise", "MultipleProgramMatchError", "(", "len", "(", "matching_programs", ")", ")", "elif", "len", "(", "matching_programs", ")", "==", "1", ":", "return", "matching_programs", "[", "0", "]", "else", ":", "return", "None" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CourseCatalogApiClient.get_program_by_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
enterprise/api_client/discovery.py
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_data( self.PROGRAMS_ENDPOINT, resource_id=program_uuid, default=None )
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_data( self.PROGRAMS_ENDPOINT, resource_id=program_uuid, default=None )
[ "Return", "single", "program", "by", "UUID", "or", "None", "if", "not", "found", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L314-L329
[ "def", "get_program_by_uuid", "(", "self", ",", "program_uuid", ")", ":", "return", "self", ".", "_load_data", "(", "self", ".", "PROGRAMS_ENDPOINT", ",", "resource_id", "=", "program_uuid", ",", "default", "=", "None", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CourseCatalogApiClient.get_program_course_keys
Get a list of the course IDs (not course run IDs) contained in the program. Arguments: program_uuid (str): Program UUID in string form Returns: list(str): List of course keys in string form that are included in the program
enterprise/api_client/discovery.py
def get_program_course_keys(self, program_uuid): """ Get a list of the course IDs (not course run IDs) contained in the program. Arguments: program_uuid (str): Program UUID in string form Returns: list(str): List of course keys in string form that are included in the program """ program_details = self.get_program_by_uuid(program_uuid) if not program_details: return [] return [course['key'] for course in program_details.get('courses', [])]
def get_program_course_keys(self, program_uuid): """ Get a list of the course IDs (not course run IDs) contained in the program. Arguments: program_uuid (str): Program UUID in string form Returns: list(str): List of course keys in string form that are included in the program """ program_details = self.get_program_by_uuid(program_uuid) if not program_details: return [] return [course['key'] for course in program_details.get('courses', [])]
[ "Get", "a", "list", "of", "the", "course", "IDs", "(", "not", "course", "run", "IDs", ")", "contained", "in", "the", "program", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L331-L345
[ "def", "get_program_course_keys", "(", "self", ",", "program_uuid", ")", ":", "program_details", "=", "self", ".", "get_program_by_uuid", "(", "program_uuid", ")", "if", "not", "program_details", ":", "return", "[", "]", "return", "[", "course", "[", "'key'", "]", "for", "course", "in", "program_details", ".", "get", "(", "'courses'", ",", "[", "]", ")", "]" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CourseCatalogApiClient.get_program_type_by_slug
Get a program type by its slug. Arguments: slug (str): The slug to identify the program type. Returns: dict: A program type object.
enterprise/api_client/discovery.py
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, resource_id=slug, default=None, )
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, resource_id=slug, default=None, )
[ "Get", "a", "program", "type", "by", "its", "slug", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L347-L362
[ "def", "get_program_type_by_slug", "(", "self", ",", "slug", ")", ":", "return", "self", ".", "_load_data", "(", "self", ".", "PROGRAM_TYPES_ENDPOINT", ",", "resource_id", "=", "slug", ",", "default", "=", "None", ",", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CourseCatalogApiClient.get_common_course_modes
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']) {} # run1 has nothing, run 2 prof, run3 has prof get_common_course_modes(['course-v1:run1', 'course-v1:run2', 'course-v1:run3']) {}
enterprise/api_client/discovery.py
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']) {} # run1 has nothing, run 2 prof, run3 has prof get_common_course_modes(['course-v1:run1', 'course-v1:run2', 'course-v1:run3']) {} """ available_course_modes = None for course_run_id in course_run_ids: course_run = self.get_course_run(course_run_id) or {} course_run_modes = {seat.get('type') for seat in course_run.get('seats', [])} if available_course_modes is None: available_course_modes = course_run_modes else: available_course_modes &= course_run_modes if not available_course_modes: return available_course_modes return available_course_modes
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']) {} # run1 has nothing, run 2 prof, run3 has prof get_common_course_modes(['course-v1:run1', 'course-v1:run2', 'course-v1:run3']) {} """ available_course_modes = None for course_run_id in course_run_ids: course_run = self.get_course_run(course_run_id) or {} course_run_modes = {seat.get('type') for seat in course_run.get('seats', [])} if available_course_modes is None: available_course_modes = course_run_modes else: available_course_modes &= course_run_modes if not available_course_modes: return available_course_modes return available_course_modes
[ "Find", "common", "course", "modes", "for", "a", "set", "of", "course", "runs", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L364-L416
[ "def", "get_common_course_modes", "(", "self", ",", "course_run_ids", ")", ":", "available_course_modes", "=", "None", "for", "course_run_id", "in", "course_run_ids", ":", "course_run", "=", "self", ".", "get_course_run", "(", "course_run_id", ")", "or", "{", "}", "course_run_modes", "=", "{", "seat", ".", "get", "(", "'type'", ")", "for", "seat", "in", "course_run", ".", "get", "(", "'seats'", ",", "[", "]", ")", "}", "if", "available_course_modes", "is", "None", ":", "available_course_modes", "=", "course_run_modes", "else", ":", "available_course_modes", "&=", "course_run_modes", "if", "not", "available_course_modes", ":", "return", "available_course_modes", "return", "available_course_modes" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CourseCatalogApiClient.is_course_in_catalog
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
enterprise/api_client/discovery.py
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)) except InvalidKeyError: course_run_id = None endpoint = self.client.catalogs(catalog_id).contains if course_run_id: resp = endpoint.get(course_run_id=course_run_id) else: resp = endpoint.get(course_id=course_id) return resp.get('courses', {}).get(course_id, False)
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)) except InvalidKeyError: course_run_id = None endpoint = self.client.catalogs(catalog_id).contains if course_run_id: resp = endpoint.get(course_run_id=course_run_id) else: resp = endpoint.get(course_id=course_id) return resp.get('courses', {}).get(course_id, False)
[ "Determine", "if", "the", "given", "course", "or", "course", "run", "ID", "is", "contained", "in", "the", "catalog", "with", "the", "given", "ID", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L418-L442
[ "def", "is_course_in_catalog", "(", "self", ",", "catalog_id", ",", "course_id", ")", ":", "try", ":", "# Determine if we have a course run ID, rather than a plain course ID", "course_run_id", "=", "str", "(", "CourseKey", ".", "from_string", "(", "course_id", ")", ")", "except", "InvalidKeyError", ":", "course_run_id", "=", "None", "endpoint", "=", "self", ".", "client", ".", "catalogs", "(", "catalog_id", ")", ".", "contains", "if", "course_run_id", ":", "resp", "=", "endpoint", ".", "get", "(", "course_run_id", "=", "course_run_id", ")", "else", ":", "resp", "=", "endpoint", ".", "get", "(", "course_id", "=", "course_id", ")", "return", "resp", ".", "get", "(", "'courses'", ",", "{", "}", ")", ".", "get", "(", "course_id", ",", "False", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CourseCatalogApiClient._load_data
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
enterprise/api_client/discovery.py
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(), resource=resource, api=self.client, **kwargs ) or default_val except (SlumberBaseException, ConnectionError, Timeout) as exc: LOGGER.exception( 'Failed to load data from resource [%s] with kwargs [%s] due to: [%s]', resource, kwargs, str(exc) ) return default_val
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(), resource=resource, api=self.client, **kwargs ) or default_val except (SlumberBaseException, ConnectionError, Timeout) as exc: LOGGER.exception( 'Failed to load data from resource [%s] with kwargs [%s] due to: [%s]', resource, kwargs, str(exc) ) return default_val
[ "Load", "data", "from", "API", "client", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/discovery.py#L444-L469
[ "def", "_load_data", "(", "self", ",", "resource", ",", "default", "=", "DEFAULT_VALUE_SAFEGUARD", ",", "*", "*", "kwargs", ")", ":", "default_val", "=", "default", "if", "default", "!=", "self", ".", "DEFAULT_VALUE_SAFEGUARD", "else", "{", "}", "try", ":", "return", "get_edx_api_data", "(", "api_config", "=", "CatalogIntegration", ".", "current", "(", ")", ",", "resource", "=", "resource", ",", "api", "=", "self", ".", "client", ",", "*", "*", "kwargs", ")", "or", "default_val", "except", "(", "SlumberBaseException", ",", "ConnectionError", ",", "Timeout", ")", "as", "exc", ":", "LOGGER", ".", "exception", "(", "'Failed to load data from resource [%s] with kwargs [%s] due to: [%s]'", ",", "resource", ",", "kwargs", ",", "str", "(", "exc", ")", ")", "return", "default_val" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnterpriseApiClient.get_content_metadata
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.
enterprise/api_client/enterprise.py
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 for enterprise_customer_catalog in enterprise_customer.enterprise_customer_catalogs.all(): response = self._load_data( self.ENTERPRISE_CUSTOMER_CATALOGS_ENDPOINT, resource_id=str(enterprise_customer_catalog.uuid), traverse_pagination=True, querystring={'page_size': 1000}, ) for item in response['results']: content_id = utils.get_content_metadata_item_id(item) content_metadata[content_id] = item return content_metadata.values()
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 for enterprise_customer_catalog in enterprise_customer.enterprise_customer_catalogs.all(): response = self._load_data( self.ENTERPRISE_CUSTOMER_CATALOGS_ENDPOINT, resource_id=str(enterprise_customer_catalog.uuid), traverse_pagination=True, querystring={'page_size': 1000}, ) for item in response['results']: content_id = utils.get_content_metadata_item_id(item) content_metadata[content_id] = item return content_metadata.values()
[ "Return", "all", "content", "metadata", "contained", "in", "the", "catalogs", "associated", "with", "the", "EnterpriseCustomer", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/enterprise.py#L33-L70
[ "def", "get_content_metadata", "(", "self", ",", "enterprise_customer", ")", ":", "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", "for", "enterprise_customer_catalog", "in", "enterprise_customer", ".", "enterprise_customer_catalogs", ".", "all", "(", ")", ":", "response", "=", "self", ".", "_load_data", "(", "self", ".", "ENTERPRISE_CUSTOMER_CATALOGS_ENDPOINT", ",", "resource_id", "=", "str", "(", "enterprise_customer_catalog", ".", "uuid", ")", ",", "traverse_pagination", "=", "True", ",", "querystring", "=", "{", "'page_size'", ":", "1000", "}", ",", ")", "for", "item", "in", "response", "[", "'results'", "]", ":", "content_id", "=", "utils", ".", "get_content_metadata_item_id", "(", "item", ")", "content_metadata", "[", "content_id", "]", "=", "item", "return", "content_metadata", ".", "values", "(", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnterpriseApiClient._load_data
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.
enterprise/api_client/enterprise.py
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: # Response is not cached, so make a call. endpoint = getattr(self.client, resource)(resource_id) endpoint = getattr(endpoint, detail_resource) if detail_resource else endpoint response = endpoint.get(**querystring) if traverse_pagination: results = utils.traverse_pagination(response, endpoint) response = { 'count': len(results), 'next': 'None', 'previous': 'None', 'results': results, } if response: # Now that we've got a response, cache it. cache.set(cache_key, response, settings.ENTERPRISE_API_CACHE_TIMEOUT) return response or default_val
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: # Response is not cached, so make a call. endpoint = getattr(self.client, resource)(resource_id) endpoint = getattr(endpoint, detail_resource) if detail_resource else endpoint response = endpoint.get(**querystring) if traverse_pagination: results = utils.traverse_pagination(response, endpoint) response = { 'count': len(results), 'next': 'None', 'previous': 'None', 'results': results, } if response: # Now that we've got a response, cache it. cache.set(cache_key, response, settings.ENTERPRISE_API_CACHE_TIMEOUT) return response or default_val
[ "Loads", "a", "response", "from", "a", "call", "to", "one", "of", "the", "Enterprise", "endpoints", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api_client/enterprise.py#L73-L119
[ "def", "_load_data", "(", "self", ",", "resource", ",", "detail_resource", "=", "None", ",", "resource_id", "=", "None", ",", "querystring", "=", "None", ",", "traverse_pagination", "=", "False", ",", "default", "=", "DEFAULT_VALUE_SAFEGUARD", ",", ")", ":", "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", ":", "# Response is not cached, so make a call.", "endpoint", "=", "getattr", "(", "self", ".", "client", ",", "resource", ")", "(", "resource_id", ")", "endpoint", "=", "getattr", "(", "endpoint", ",", "detail_resource", ")", "if", "detail_resource", "else", "endpoint", "response", "=", "endpoint", ".", "get", "(", "*", "*", "querystring", ")", "if", "traverse_pagination", ":", "results", "=", "utils", ".", "traverse_pagination", "(", "response", ",", "endpoint", ")", "response", "=", "{", "'count'", ":", "len", "(", "results", ")", ",", "'next'", ":", "'None'", ",", "'previous'", ":", "'None'", ",", "'results'", ":", "results", ",", "}", "if", "response", ":", "# Now that we've got a response, cache it.", "cache", ".", "set", "(", "cache_key", ",", "response", ",", "settings", ".", "ENTERPRISE_API_CACHE_TIMEOUT", ")", "return", "response", "or", "default_val" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
ContentMetadataTransmitter.transmit
Transmit content metadata items to the integrated channel.
integrated_channels/integrated_channel/transmitters/content_metadata.py
def transmit(self, payload, **kwargs): """ Transmit content metadata items to the integrated channel. """ items_to_create, items_to_update, items_to_delete, transmission_map = self._partition_items(payload) self._transmit_delete(items_to_delete) self._transmit_create(items_to_create) self._transmit_update(items_to_update, transmission_map)
def transmit(self, payload, **kwargs): """ Transmit content metadata items to the integrated channel. """ items_to_create, items_to_update, items_to_delete, transmission_map = self._partition_items(payload) self._transmit_delete(items_to_delete) self._transmit_create(items_to_create) self._transmit_update(items_to_update, transmission_map)
[ "Transmit", "content", "metadata", "items", "to", "the", "integrated", "channel", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L37-L44
[ "def", "transmit", "(", "self", ",", "payload", ",", "*", "*", "kwargs", ")", ":", "items_to_create", ",", "items_to_update", ",", "items_to_delete", ",", "transmission_map", "=", "self", ".", "_partition_items", "(", "payload", ")", "self", ".", "_transmit_delete", "(", "items_to_delete", ")", "self", ".", "_transmit_create", "(", "items_to_create", ")", "self", ".", "_transmit_update", "(", "items_to_update", ",", "transmission_map", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
ContentMetadataTransmitter._partition_items
Return items that need to be created, updated, and deleted along with the current ContentMetadataItemTransmissions.
integrated_channels/integrated_channel/transmitters/content_metadata.py
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 else: items_to_create[content_id] = channel_metadata LOGGER.info( 'Preparing to transmit creation of [%s] content metadata items with plugin configuration [%s]: [%s]', len(items_to_create), self.enterprise_configuration, items_to_create.keys(), ) LOGGER.info( 'Preparing to transmit update of [%s] content metadata items with plugin configuration [%s]: [%s]', len(items_to_update), self.enterprise_configuration, items_to_update.keys(), ) LOGGER.info( 'Preparing to transmit deletion of [%s] content metadata items with plugin configuration [%s]: [%s]', len(items_to_delete), self.enterprise_configuration, items_to_delete.keys(), ) return items_to_create, items_to_update, items_to_delete, transmission_map
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 else: items_to_create[content_id] = channel_metadata LOGGER.info( 'Preparing to transmit creation of [%s] content metadata items with plugin configuration [%s]: [%s]', len(items_to_create), self.enterprise_configuration, items_to_create.keys(), ) LOGGER.info( 'Preparing to transmit update of [%s] content metadata items with plugin configuration [%s]: [%s]', len(items_to_update), self.enterprise_configuration, items_to_update.keys(), ) LOGGER.info( 'Preparing to transmit deletion of [%s] content metadata items with plugin configuration [%s]: [%s]', len(items_to_delete), self.enterprise_configuration, items_to_delete.keys(), ) return items_to_create, items_to_update, items_to_delete, transmission_map
[ "Return", "items", "that", "need", "to", "be", "created", "updated", "and", "deleted", "along", "with", "the", "current", "ContentMetadataItemTransmissions", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L46-L96
[ "def", "_partition_items", "(", "self", ",", "channel_metadata_item_map", ")", ":", "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", "else", ":", "items_to_create", "[", "content_id", "]", "=", "channel_metadata", "LOGGER", ".", "info", "(", "'Preparing to transmit creation of [%s] content metadata items with plugin configuration [%s]: [%s]'", ",", "len", "(", "items_to_create", ")", ",", "self", ".", "enterprise_configuration", ",", "items_to_create", ".", "keys", "(", ")", ",", ")", "LOGGER", ".", "info", "(", "'Preparing to transmit update of [%s] content metadata items with plugin configuration [%s]: [%s]'", ",", "len", "(", "items_to_update", ")", ",", "self", ".", "enterprise_configuration", ",", "items_to_update", ".", "keys", "(", ")", ",", ")", "LOGGER", ".", "info", "(", "'Preparing to transmit deletion of [%s] content metadata items with plugin configuration [%s]: [%s]'", ",", "len", "(", "items_to_delete", ")", ",", "self", ".", "enterprise_configuration", ",", "items_to_delete", ".", "keys", "(", ")", ",", ")", "return", "items_to_create", ",", "items_to_update", ",", "items_to_delete", ",", "transmission_map" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
ContentMetadataTransmitter._serialize_items
Serialize content metadata items for a create transmission to the integrated channel.
integrated_channels/integrated_channel/transmitters/content_metadata.py
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-8')
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-8')
[ "Serialize", "content", "metadata", "items", "for", "a", "create", "transmission", "to", "the", "integrated", "channel", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L107-L114
[ "def", "_serialize_items", "(", "self", ",", "channel_metadata_items", ")", ":", "return", "json", ".", "dumps", "(", "self", ".", "_prepare_items_for_transmission", "(", "channel_metadata_items", ")", ",", "sort_keys", "=", "True", ")", ".", "encode", "(", "'utf-8'", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
ContentMetadataTransmitter._transmit_create
Transmit content metadata creation to integrated channel.
integrated_channels/integrated_channel/transmitters/content_metadata.py
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 for integrated channel [%s] [%s]', len(chunk), self.enterprise_configuration.enterprise_customer.name, self.enterprise_configuration.channel_code, ) LOGGER.error(exc) else: self._create_transmissions(chunk)
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 for integrated channel [%s] [%s]', len(chunk), self.enterprise_configuration.enterprise_customer.name, self.enterprise_configuration.channel_code, ) LOGGER.error(exc) else: self._create_transmissions(chunk)
[ "Transmit", "content", "metadata", "creation", "to", "integrated", "channel", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L116-L133
[ "def", "_transmit_create", "(", "self", ",", "channel_metadata_item_map", ")", ":", "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 for integrated channel [%s] [%s]'", ",", "len", "(", "chunk", ")", ",", "self", ".", "enterprise_configuration", ".", "enterprise_customer", ".", "name", ",", "self", ".", "enterprise_configuration", ".", "channel_code", ",", ")", "LOGGER", ".", "error", "(", "exc", ")", "else", ":", "self", ".", "_create_transmissions", "(", "chunk", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
ContentMetadataTransmitter._transmit_update
Transmit content metadata update to integrated channel.
integrated_channels/integrated_channel/transmitters/content_metadata.py
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 metadata items for integrated channel [%s] [%s]', len(chunk), self.enterprise_configuration.enterprise_customer.name, self.enterprise_configuration.channel_code, ) LOGGER.error(exc) else: self._update_transmissions(chunk, transmission_map)
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 metadata items for integrated channel [%s] [%s]', len(chunk), self.enterprise_configuration.enterprise_customer.name, self.enterprise_configuration.channel_code, ) LOGGER.error(exc) else: self._update_transmissions(chunk, transmission_map)
[ "Transmit", "content", "metadata", "update", "to", "integrated", "channel", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L135-L152
[ "def", "_transmit_update", "(", "self", ",", "channel_metadata_item_map", ",", "transmission_map", ")", ":", "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 metadata items for integrated channel [%s] [%s]'", ",", "len", "(", "chunk", ")", ",", "self", ".", "enterprise_configuration", ".", "enterprise_customer", ".", "name", ",", "self", ".", "enterprise_configuration", ".", "channel_code", ",", ")", "LOGGER", ".", "error", "(", "exc", ")", "else", ":", "self", ".", "_update_transmissions", "(", "chunk", ",", "transmission_map", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
ContentMetadataTransmitter._transmit_delete
Transmit content metadata deletion to integrated channel.
integrated_channels/integrated_channel/transmitters/content_metadata.py
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 [%s] [%s]', len(chunk), self.enterprise_configuration.enterprise_customer.name, self.enterprise_configuration.channel_code, ) LOGGER.error(exc) else: self._delete_transmissions(chunk.keys())
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 [%s] [%s]', len(chunk), self.enterprise_configuration.enterprise_customer.name, self.enterprise_configuration.channel_code, ) LOGGER.error(exc) else: self._delete_transmissions(chunk.keys())
[ "Transmit", "content", "metadata", "deletion", "to", "integrated", "channel", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L154-L171
[ "def", "_transmit_delete", "(", "self", ",", "channel_metadata_item_map", ")", ":", "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 [%s] [%s]'", ",", "len", "(", "chunk", ")", ",", "self", ".", "enterprise_configuration", ".", "enterprise_customer", ".", "name", ",", "self", ".", "enterprise_configuration", ".", "channel_code", ",", ")", "LOGGER", ".", "error", "(", "exc", ")", "else", ":", "self", ".", "_delete_transmissions", "(", "chunk", ".", "keys", "(", ")", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
ContentMetadataTransmitter._get_transmissions
Return the ContentMetadataItemTransmision models for previously transmitted content metadata items.
integrated_channels/integrated_channel/transmitters/content_metadata.py
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' ) return ContentMetadataItemTransmission.objects.filter( enterprise_customer=self.enterprise_configuration.enterprise_customer, integrated_channel_code=self.enterprise_configuration.channel_code() )
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' ) return ContentMetadataItemTransmission.objects.filter( enterprise_customer=self.enterprise_configuration.enterprise_customer, integrated_channel_code=self.enterprise_configuration.channel_code() )
[ "Return", "the", "ContentMetadataItemTransmision", "models", "for", "previously", "transmitted", "content", "metadata", "items", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L173-L186
[ "def", "_get_transmissions", "(", "self", ")", ":", "# pylint: disable=invalid-name", "ContentMetadataItemTransmission", "=", "apps", ".", "get_model", "(", "'integrated_channel'", ",", "'ContentMetadataItemTransmission'", ")", "return", "ContentMetadataItemTransmission", ".", "objects", ".", "filter", "(", "enterprise_customer", "=", "self", ".", "enterprise_configuration", ".", "enterprise_customer", ",", "integrated_channel_code", "=", "self", ".", "enterprise_configuration", ".", "channel_code", "(", ")", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
ContentMetadataTransmitter._create_transmissions
Create ContentMetadataItemTransmision models for the given content metadata items.
integrated_channels/integrated_channel/transmitters/content_metadata.py
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, integrated_channel_code=self.enterprise_configuration.channel_code(), content_id=content_id, channel_metadata=channel_metadata ) ) ContentMetadataItemTransmission.objects.bulk_create(transmissions)
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, integrated_channel_code=self.enterprise_configuration.channel_code(), content_id=content_id, channel_metadata=channel_metadata ) ) ContentMetadataItemTransmission.objects.bulk_create(transmissions)
[ "Create", "ContentMetadataItemTransmision", "models", "for", "the", "given", "content", "metadata", "items", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L188-L207
[ "def", "_create_transmissions", "(", "self", ",", "content_metadata_item_map", ")", ":", "# 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", ",", "integrated_channel_code", "=", "self", ".", "enterprise_configuration", ".", "channel_code", "(", ")", ",", "content_id", "=", "content_id", ",", "channel_metadata", "=", "channel_metadata", ")", ")", "ContentMetadataItemTransmission", ".", "objects", ".", "bulk_create", "(", "transmissions", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
ContentMetadataTransmitter._update_transmissions
Update ContentMetadataItemTransmision models for the given content metadata items.
integrated_channels/integrated_channel/transmitters/content_metadata.py
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[content_id] transmission.channel_metadata = channel_metadata transmission.save()
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[content_id] transmission.channel_metadata = channel_metadata transmission.save()
[ "Update", "ContentMetadataItemTransmision", "models", "for", "the", "given", "content", "metadata", "items", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L209-L216
[ "def", "_update_transmissions", "(", "self", ",", "content_metadata_item_map", ",", "transmission_map", ")", ":", "for", "content_id", ",", "channel_metadata", "in", "content_metadata_item_map", ".", "items", "(", ")", ":", "transmission", "=", "transmission_map", "[", "content_id", "]", "transmission", ".", "channel_metadata", "=", "channel_metadata", "transmission", ".", "save", "(", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
ContentMetadataTransmitter._delete_transmissions
Delete ContentMetadataItemTransmision models associated with the given content metadata items.
integrated_channels/integrated_channel/transmitters/content_metadata.py
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' ) ContentMetadataItemTransmission.objects.filter( enterprise_customer=self.enterprise_configuration.enterprise_customer, integrated_channel_code=self.enterprise_configuration.channel_code(), content_id__in=content_metadata_item_ids ).delete()
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' ) ContentMetadataItemTransmission.objects.filter( enterprise_customer=self.enterprise_configuration.enterprise_customer, integrated_channel_code=self.enterprise_configuration.channel_code(), content_id__in=content_metadata_item_ids ).delete()
[ "Delete", "ContentMetadataItemTransmision", "models", "associated", "with", "the", "given", "content", "metadata", "items", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/integrated_channel/transmitters/content_metadata.py#L218-L231
[ "def", "_delete_transmissions", "(", "self", ",", "content_metadata_item_ids", ")", ":", "# pylint: disable=invalid-name", "ContentMetadataItemTransmission", "=", "apps", ".", "get_model", "(", "'integrated_channel'", ",", "'ContentMetadataItemTransmission'", ")", "ContentMetadataItemTransmission", ".", "objects", ".", "filter", "(", "enterprise_customer", "=", "self", ".", "enterprise_configuration", ".", "enterprise_customer", ",", "integrated_channel_code", "=", "self", ".", "enterprise_configuration", ".", "channel_code", "(", ")", ",", "content_id__in", "=", "content_metadata_item_ids", ")", ".", "delete", "(", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
deprecated
Flag a method as deprecated. :param extra: Extra text you'd like to display after the default text.
enterprise/decorators.py
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 ) frame = inspect.currentframe().f_back warnings.warn_explicit( message, category=DeprecationWarning, filename=inspect.getfile(frame.f_code), lineno=frame.f_lineno ) return func(*args, **kwargs) return wrapper return decorator
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 ) frame = inspect.currentframe().f_back warnings.warn_explicit( message, category=DeprecationWarning, filename=inspect.getfile(frame.f_code), lineno=frame.f_lineno ) return func(*args, **kwargs) return wrapper return decorator
[ "Flag", "a", "method", "as", "deprecated", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/decorators.py#L22-L50
[ "def", "deprecated", "(", "extra", ")", ":", "def", "decorator", "(", "func", ")", ":", "\"\"\"\n Return a decorated function that emits a deprecation warning on use.\n \"\"\"", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Wrap the function.\n \"\"\"", "message", "=", "'You called the deprecated function `{function}`. {extra}'", ".", "format", "(", "function", "=", "func", ".", "__name__", ",", "extra", "=", "extra", ")", "frame", "=", "inspect", ".", "currentframe", "(", ")", ".", "f_back", "warnings", ".", "warn_explicit", "(", "message", ",", "category", "=", "DeprecationWarning", ",", "filename", "=", "inspect", ".", "getfile", "(", "frame", ".", "f_code", ")", ",", "lineno", "=", "frame", ".", "f_lineno", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "decorator" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
ignore_warning
Ignore any emitted warnings from a function. :param warning: The category of warning to ignore.
enterprise/decorators.py
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): """ Wrap the function. """ warnings.simplefilter('ignore', warning) return func(*args, **kwargs) return wrapper return decorator
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): """ Wrap the function. """ warnings.simplefilter('ignore', warning) return func(*args, **kwargs) return wrapper return decorator
[ "Ignore", "any", "emitted", "warnings", "from", "a", "function", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/decorators.py#L53-L71
[ "def", "ignore_warning", "(", "warning", ")", ":", "def", "decorator", "(", "func", ")", ":", "\"\"\"\n Return a decorated function whose emitted warnings are ignored.\n \"\"\"", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Wrap the function.\n \"\"\"", "warnings", ".", "simplefilter", "(", "'ignore'", ",", "warning", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "decorator" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
enterprise_login_required
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 ...
enterprise/decorators.py
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 request.user.is_authenticated: parsed_current_url = urlparse(request.get_full_path()) parsed_query_string = parse_qs(parsed_current_url.query) parsed_query_string.update({ 'tpa_hint': enterprise_customer.identity_provider, FRESH_LOGIN_PARAMETER: 'yes' }) next_url = '{current_path}?{query_string}'.format( current_path=quote(parsed_current_url.path), query_string=urlencode(parsed_query_string, doseq=True) ) return redirect( '{login_url}?{params}'.format( login_url='/login', params=urlencode( {'next': next_url} ) ) ) # Otherwise, they can proceed to the original view. return view(request, *args, **kwargs) return wrapper
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 request.user.is_authenticated: parsed_current_url = urlparse(request.get_full_path()) parsed_query_string = parse_qs(parsed_current_url.query) parsed_query_string.update({ 'tpa_hint': enterprise_customer.identity_provider, FRESH_LOGIN_PARAMETER: 'yes' }) next_url = '{current_path}?{query_string}'.format( current_path=quote(parsed_current_url.path), query_string=urlencode(parsed_query_string, doseq=True) ) return redirect( '{login_url}?{params}'.format( login_url='/login', params=urlencode( {'next': next_url} ) ) ) # Otherwise, they can proceed to the original view. return view(request, *args, **kwargs) return wrapper
[ "View", "decorator", "for", "allowing", "authenticated", "user", "with", "valid", "enterprise", "UUID", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/decorators.py#L93-L158
[ "def", "enterprise_login_required", "(", "view", ")", ":", "@", "wraps", "(", "view", ")", "def", "wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Wrap the decorator.\n \"\"\"", "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", "request", ".", "user", ".", "is_authenticated", ":", "parsed_current_url", "=", "urlparse", "(", "request", ".", "get_full_path", "(", ")", ")", "parsed_query_string", "=", "parse_qs", "(", "parsed_current_url", ".", "query", ")", "parsed_query_string", ".", "update", "(", "{", "'tpa_hint'", ":", "enterprise_customer", ".", "identity_provider", ",", "FRESH_LOGIN_PARAMETER", ":", "'yes'", "}", ")", "next_url", "=", "'{current_path}?{query_string}'", ".", "format", "(", "current_path", "=", "quote", "(", "parsed_current_url", ".", "path", ")", ",", "query_string", "=", "urlencode", "(", "parsed_query_string", ",", "doseq", "=", "True", ")", ")", "return", "redirect", "(", "'{login_url}?{params}'", ".", "format", "(", "login_url", "=", "'/login'", ",", "params", "=", "urlencode", "(", "{", "'next'", ":", "next_url", "}", ")", ")", ")", "# Otherwise, they can proceed to the original view.", "return", "view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
force_fresh_session
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 ...
enterprise/decorators.py
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 here again. enterprise_customer = get_enterprise_customer_or_404(kwargs.get('enterprise_uuid')) provider_id = enterprise_customer.identity_provider or '' sso_provider = get_identity_provider(provider_id) if sso_provider: # Parse the current request full path, quote just the path portion, # then reconstruct the full path string. # The path and query portions should be the only non-empty strings here. scheme, netloc, path, params, query, fragment = urlparse(request.get_full_path()) redirect_url = urlunparse((scheme, netloc, quote(path), params, query, fragment)) return redirect( '{logout_url}?{params}'.format( logout_url='/logout', params=urlencode( {'redirect_url': redirect_url} ) ) ) return view(request, *args, **kwargs) return wrapper
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 here again. enterprise_customer = get_enterprise_customer_or_404(kwargs.get('enterprise_uuid')) provider_id = enterprise_customer.identity_provider or '' sso_provider = get_identity_provider(provider_id) if sso_provider: # Parse the current request full path, quote just the path portion, # then reconstruct the full path string. # The path and query portions should be the only non-empty strings here. scheme, netloc, path, params, query, fragment = urlparse(request.get_full_path()) redirect_url = urlunparse((scheme, netloc, quote(path), params, query, fragment)) return redirect( '{logout_url}?{params}'.format( logout_url='/logout', params=urlencode( {'redirect_url': redirect_url} ) ) ) return view(request, *args, **kwargs) return wrapper
[ "View", "decorator", "which", "terminates", "stale", "TPA", "sessions", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/decorators.py#L161-L221
[ "def", "force_fresh_session", "(", "view", ")", ":", "@", "wraps", "(", "view", ")", "def", "wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Wrap the function.\n \"\"\"", "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 here again.", "enterprise_customer", "=", "get_enterprise_customer_or_404", "(", "kwargs", ".", "get", "(", "'enterprise_uuid'", ")", ")", "provider_id", "=", "enterprise_customer", ".", "identity_provider", "or", "''", "sso_provider", "=", "get_identity_provider", "(", "provider_id", ")", "if", "sso_provider", ":", "# Parse the current request full path, quote just the path portion,", "# then reconstruct the full path string.", "# The path and query portions should be the only non-empty strings here.", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", "=", "urlparse", "(", "request", ".", "get_full_path", "(", ")", ")", "redirect_url", "=", "urlunparse", "(", "(", "scheme", ",", "netloc", ",", "quote", "(", "path", ")", ",", "params", ",", "query", ",", "fragment", ")", ")", "return", "redirect", "(", "'{logout_url}?{params}'", ".", "format", "(", "logout_url", "=", "'/logout'", ",", "params", "=", "urlencode", "(", "{", "'redirect_url'", ":", "redirect_url", "}", ")", ")", ")", "return", "view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnterpriseCourseEnrollmentWriteSerializer.validate_username
Verify that the username has a matching user, and that the user has an associated EnterpriseCustomerUser.
enterprise/api/v1/serializers.py
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: enterprise_customer_user = models.EnterpriseCustomerUser.objects.get(user_id=user.pk) except models.EnterpriseCustomerUser.DoesNotExist: raise serializers.ValidationError("User has no EnterpriseCustomerUser") self.enterprise_customer_user = enterprise_customer_user return value
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: enterprise_customer_user = models.EnterpriseCustomerUser.objects.get(user_id=user.pk) except models.EnterpriseCustomerUser.DoesNotExist: raise serializers.ValidationError("User has no EnterpriseCustomerUser") self.enterprise_customer_user = enterprise_customer_user return value
[ "Verify", "that", "the", "username", "has", "a", "matching", "user", "and", "that", "the", "user", "has", "an", "associated", "EnterpriseCustomerUser", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L156-L171
[ "def", "validate_username", "(", "self", ",", "value", ")", ":", "try", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "username", "=", "value", ")", "except", "User", ".", "DoesNotExist", ":", "raise", "serializers", ".", "ValidationError", "(", "\"User does not exist\"", ")", "try", ":", "enterprise_customer_user", "=", "models", ".", "EnterpriseCustomerUser", ".", "objects", ".", "get", "(", "user_id", "=", "user", ".", "pk", ")", "except", "models", ".", "EnterpriseCustomerUser", ".", "DoesNotExist", ":", "raise", "serializers", ".", "ValidationError", "(", "\"User has no EnterpriseCustomerUser\"", ")", "self", ".", "enterprise_customer_user", "=", "enterprise_customer_user", "return", "value" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnterpriseCourseEnrollmentWriteSerializer.save
Save the model with the found EnterpriseCustomerUser.
enterprise/api/v1/serializers.py
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, course_id=course_id, ) if created: track_enrollment('rest-api-enrollment', self.enterprise_customer_user.user_id, course_id)
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, course_id=course_id, ) if created: track_enrollment('rest-api-enrollment', self.enterprise_customer_user.user_id, course_id)
[ "Save", "the", "model", "with", "the", "found", "EnterpriseCustomerUser", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L173-L184
[ "def", "save", "(", "self", ")", ":", "# pylint: disable=arguments-differ", "course_id", "=", "self", ".", "validated_data", "[", "'course_id'", "]", "__", ",", "created", "=", "models", ".", "EnterpriseCourseEnrollment", ".", "objects", ".", "get_or_create", "(", "enterprise_customer_user", "=", "self", ".", "enterprise_customer_user", ",", "course_id", "=", "course_id", ",", ")", "if", "created", ":", "track_enrollment", "(", "'rest-api-enrollment'", ",", "self", ".", "enterprise_customer_user", ".", "user_id", ",", "course_id", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnterpriseCustomerCatalogDetailSerializer.to_representation
Serialize the EnterpriseCustomerCatalog object. Arguments: instance (EnterpriseCustomerCatalog): The EnterpriseCustomerCatalog to serialize. Returns: dict: The EnterpriseCustomerCatalog converted to a dict.
enterprise/api/v1/serializers.py
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']) if content_type == 'courserun': item['enrollment_url'] = instance.get_course_run_enrollment_url(item['key']) if content_type == 'program': item['enrollment_url'] = instance.get_program_enrollment_url(item['uuid']) # Build pagination URLs previous_url = None next_url = None page = int(request.GET.get('page', '1')) request_uri = request.build_absolute_uri() if paginated_content['previous']: previous_url = utils.update_query_parameters(request_uri, {'page': page - 1}) if paginated_content['next']: next_url = utils.update_query_parameters(request_uri, {'page': page + 1}) representation['count'] = count representation['previous'] = previous_url representation['next'] = next_url representation['results'] = search_results return representation
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']) if content_type == 'courserun': item['enrollment_url'] = instance.get_course_run_enrollment_url(item['key']) if content_type == 'program': item['enrollment_url'] = instance.get_program_enrollment_url(item['uuid']) # Build pagination URLs previous_url = None next_url = None page = int(request.GET.get('page', '1')) request_uri = request.build_absolute_uri() if paginated_content['previous']: previous_url = utils.update_query_parameters(request_uri, {'page': page - 1}) if paginated_content['next']: next_url = utils.update_query_parameters(request_uri, {'page': page + 1}) representation['count'] = count representation['previous'] = previous_url representation['next'] = next_url representation['results'] = search_results return representation
[ "Serialize", "the", "EnterpriseCustomerCatalog", "object", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L205-L255
[ "def", "to_representation", "(", "self", ",", "instance", ")", ":", "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'", "]", ")", "if", "content_type", "==", "'courserun'", ":", "item", "[", "'enrollment_url'", "]", "=", "instance", ".", "get_course_run_enrollment_url", "(", "item", "[", "'key'", "]", ")", "if", "content_type", "==", "'program'", ":", "item", "[", "'enrollment_url'", "]", "=", "instance", ".", "get_program_enrollment_url", "(", "item", "[", "'uuid'", "]", ")", "# Build pagination URLs", "previous_url", "=", "None", "next_url", "=", "None", "page", "=", "int", "(", "request", ".", "GET", ".", "get", "(", "'page'", ",", "'1'", ")", ")", "request_uri", "=", "request", ".", "build_absolute_uri", "(", ")", "if", "paginated_content", "[", "'previous'", "]", ":", "previous_url", "=", "utils", ".", "update_query_parameters", "(", "request_uri", ",", "{", "'page'", ":", "page", "-", "1", "}", ")", "if", "paginated_content", "[", "'next'", "]", ":", "next_url", "=", "utils", ".", "update_query_parameters", "(", "request_uri", ",", "{", "'page'", ":", "page", "+", "1", "}", ")", "representation", "[", "'count'", "]", "=", "count", "representation", "[", "'previous'", "]", "=", "previous_url", "representation", "[", "'next'", "]", "=", "next_url", "representation", "[", "'results'", "]", "=", "search_results", "return", "representation" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnterpriseCustomerUserReadOnlySerializer.get_groups
Return the enterprise related django groups that this user is a part of.
enterprise/api/v1/serializers.py
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 []
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 []
[ "Return", "the", "enterprise", "related", "django", "groups", "that", "this", "user", "is", "a", "part", "of", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L286-L292
[ "def", "get_groups", "(", "self", ",", "obj", ")", ":", "if", "obj", ".", "user", ":", "return", "[", "group", ".", "name", "for", "group", "in", "obj", ".", "user", ".", "groups", ".", "filter", "(", "name__in", "=", "ENTERPRISE_PERMISSION_GROUPS", ")", "]", "return", "[", "]" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnterpriseCustomerUserWriteSerializer.validate_username
Verify that the username has a matching user.
enterprise/api/v1/serializers.py
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
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
[ "Verify", "that", "the", "username", "has", "a", "matching", "user", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L309-L318
[ "def", "validate_username", "(", "self", ",", "value", ")", ":", "try", ":", "self", ".", "user", "=", "User", ".", "objects", ".", "get", "(", "username", "=", "value", ")", "except", "User", ".", "DoesNotExist", ":", "raise", "serializers", ".", "ValidationError", "(", "\"User does not exist\"", ")", "return", "value" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnterpriseCustomerUserWriteSerializer.save
Save the EnterpriseCustomerUser.
enterprise/api/v1/serializers.py
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_customer, ) ecu.save()
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_customer, ) ecu.save()
[ "Save", "the", "EnterpriseCustomerUser", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L320-L330
[ "def", "save", "(", "self", ")", ":", "# pylint: disable=arguments-differ", "enterprise_customer", "=", "self", ".", "validated_data", "[", "'enterprise_customer'", "]", "ecu", "=", "models", ".", "EnterpriseCustomerUser", "(", "user_id", "=", "self", ".", "user", ".", "pk", ",", "enterprise_customer", "=", "enterprise_customer", ",", ")", "ecu", ".", "save", "(", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CourseDetailSerializer.to_representation
Return the updated course data dictionary. Arguments: instance (dict): The course data. Returns: dict: The updated course data.
enterprise/api/v1/serializers.py
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'] ) for course_run in updated_course['course_runs']: course_run['enrollment_url'] = enterprise_customer_catalog.get_course_run_enrollment_url( course_run['key'] ) return updated_course
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'] ) for course_run in updated_course['course_runs']: course_run['enrollment_url'] = enterprise_customer_catalog.get_course_run_enrollment_url( course_run['key'] ) return updated_course
[ "Return", "the", "updated", "course", "data", "dictionary", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L382-L401
[ "def", "to_representation", "(", "self", ",", "instance", ")", ":", "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'", "]", ")", "for", "course_run", "in", "updated_course", "[", "'course_runs'", "]", ":", "course_run", "[", "'enrollment_url'", "]", "=", "enterprise_customer_catalog", ".", "get_course_run_enrollment_url", "(", "course_run", "[", "'key'", "]", ")", "return", "updated_course" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
CourseRunDetailSerializer.to_representation
Return the updated course run data dictionary. Arguments: instance (dict): The course run data. Returns: dict: The updated course run data.
enterprise/api/v1/serializers.py
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'] updated_course_run['enrollment_url'] = enterprise_customer_catalog.get_course_run_enrollment_url( updated_course_run['key'] ) return updated_course_run
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'] updated_course_run['enrollment_url'] = enterprise_customer_catalog.get_course_run_enrollment_url( updated_course_run['key'] ) return updated_course_run
[ "Return", "the", "updated", "course", "run", "data", "dictionary", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L412-L427
[ "def", "to_representation", "(", "self", ",", "instance", ")", ":", "updated_course_run", "=", "copy", ".", "deepcopy", "(", "instance", ")", "enterprise_customer_catalog", "=", "self", ".", "context", "[", "'enterprise_customer_catalog'", "]", "updated_course_run", "[", "'enrollment_url'", "]", "=", "enterprise_customer_catalog", ".", "get_course_run_enrollment_url", "(", "updated_course_run", "[", "'key'", "]", ")", "return", "updated_course_run" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
ProgramDetailSerializer.to_representation
Return the updated program data dictionary. Arguments: instance (dict): The program data. Returns: dict: The updated program data.
enterprise/api/v1/serializers.py
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'] ) for course in updated_program['courses']: course['enrollment_url'] = enterprise_customer_catalog.get_course_enrollment_url(course['key']) for course_run in course['course_runs']: course_run['enrollment_url'] = enterprise_customer_catalog.get_course_run_enrollment_url( course_run['key'] ) return updated_program
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'] ) for course in updated_program['courses']: course['enrollment_url'] = enterprise_customer_catalog.get_course_enrollment_url(course['key']) for course_run in course['course_runs']: course_run['enrollment_url'] = enterprise_customer_catalog.get_course_run_enrollment_url( course_run['key'] ) return updated_program
[ "Return", "the", "updated", "program", "data", "dictionary", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L438-L459
[ "def", "to_representation", "(", "self", ",", "instance", ")", ":", "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'", "]", ")", "for", "course", "in", "updated_program", "[", "'courses'", "]", ":", "course", "[", "'enrollment_url'", "]", "=", "enterprise_customer_catalog", ".", "get_course_enrollment_url", "(", "course", "[", "'key'", "]", ")", "for", "course_run", "in", "course", "[", "'course_runs'", "]", ":", "course_run", "[", "'enrollment_url'", "]", "=", "enterprise_customer_catalog", ".", "get_course_run_enrollment_url", "(", "course_run", "[", "'key'", "]", ")", "return", "updated_program" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnterpriseCustomerCourseEnrollmentsListSerializer.to_internal_value
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.
enterprise/api/v1/serializers.py
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] }) ret = [] for item in data: try: validated = self.child.run_validation(item) except serializers.ValidationError as exc: ret.append(exc.detail) else: ret.append(validated) return ret
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] }) ret = [] for item in data: try: validated = self.child.run_validation(item) except serializers.ValidationError as exc: ret.append(exc.detail) else: ret.append(validated) return ret
[ "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", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L491-L515
[ "def", "to_internal_value", "(", "self", ",", "data", ")", ":", "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", "]", "}", ")", "ret", "=", "[", "]", "for", "item", "in", "data", ":", "try", ":", "validated", "=", "self", ".", "child", ".", "run_validation", "(", "item", ")", "except", "serializers", ".", "ValidationError", "as", "exc", ":", "ret", ".", "append", "(", "exc", ".", "detail", ")", "else", ":", "ret", ".", "append", "(", "validated", ")", "return", "ret" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnterpriseCustomerCourseEnrollmentsListSerializer.create
This selectively calls the child create method based on whether or not validation failed for each payload.
enterprise/api/v1/serializers.py
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 field in attrs): ret.append(self.child.create(attrs)) else: ret.append(attrs) return ret
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 field in attrs): ret.append(self.child.create(attrs)) else: ret.append(attrs) return ret
[ "This", "selectively", "calls", "the", "child", "create", "method", "based", "on", "whether", "or", "not", "validation", "failed", "for", "each", "payload", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L517-L528
[ "def", "create", "(", "self", ",", "validated_data", ")", ":", "ret", "=", "[", "]", "for", "attrs", "in", "validated_data", ":", "if", "'non_field_errors'", "not", "in", "attrs", "and", "not", "any", "(", "isinstance", "(", "attrs", "[", "field", "]", ",", "list", ")", "for", "field", "in", "attrs", ")", ":", "ret", ".", "append", "(", "self", ".", "child", ".", "create", "(", "attrs", ")", ")", "else", ":", "ret", ".", "append", "(", "attrs", ")", "return", "ret" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnterpriseCustomerCourseEnrollmentsListSerializer.to_representation
This selectively calls to_representation on each result that was processed by create.
enterprise/api/v1/serializers.py
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 ]
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 ]
[ "This", "selectively", "calls", "to_representation", "on", "each", "result", "that", "was", "processed", "by", "create", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L530-L536
[ "def", "to_representation", "(", "self", ",", "data", ")", ":", "return", "[", "self", ".", "child", ".", "to_representation", "(", "item", ")", "if", "'detail'", "in", "item", "else", "item", "for", "item", "in", "data", "]" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnterpriseCustomerCourseEnrollmentsSerializer.create
Perform the enrollment for existing enterprise customer users, or create the pending objects for new users.
enterprise/api/v1/serializers.py
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) return validated_data if is_active: track_enrollment('enterprise-customer-enrollment-api', enterprise_customer_user.user_id, course_run_id) else: if is_active: enterprise_customer_user = enterprise_customer.enroll_user_pending_registration( user_email, course_mode, course_run_id, cohort=cohort ) else: enterprise_customer.clear_pending_registration(user_email, course_run_id) if email_students: enterprise_customer.notify_enrolled_learners( self.context.get('request_user'), course_run_id, [enterprise_customer_user] ) validated_data['detail'] = 'success' return validated_data
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) return validated_data if is_active: track_enrollment('enterprise-customer-enrollment-api', enterprise_customer_user.user_id, course_run_id) else: if is_active: enterprise_customer_user = enterprise_customer.enroll_user_pending_registration( user_email, course_mode, course_run_id, cohort=cohort ) else: enterprise_customer.clear_pending_registration(user_email, course_run_id) if email_students: enterprise_customer.notify_enrolled_learners( self.context.get('request_user'), course_run_id, [enterprise_customer_user] ) validated_data['detail'] = 'success' return validated_data
[ "Perform", "the", "enrollment", "for", "existing", "enterprise", "customer", "users", "or", "create", "the", "pending", "objects", "for", "new", "users", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L567-L616
[ "def", "create", "(", "self", ",", "validated_data", ")", ":", "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", ")", "return", "validated_data", "if", "is_active", ":", "track_enrollment", "(", "'enterprise-customer-enrollment-api'", ",", "enterprise_customer_user", ".", "user_id", ",", "course_run_id", ")", "else", ":", "if", "is_active", ":", "enterprise_customer_user", "=", "enterprise_customer", ".", "enroll_user_pending_registration", "(", "user_email", ",", "course_mode", ",", "course_run_id", ",", "cohort", "=", "cohort", ")", "else", ":", "enterprise_customer", ".", "clear_pending_registration", "(", "user_email", ",", "course_run_id", ")", "if", "email_students", ":", "enterprise_customer", ".", "notify_enrolled_learners", "(", "self", ".", "context", ".", "get", "(", "'request_user'", ")", ",", "course_run_id", ",", "[", "enterprise_customer_user", "]", ")", "validated_data", "[", "'detail'", "]", "=", "'success'", "return", "validated_data" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnterpriseCustomerCourseEnrollmentsSerializer.validate_lms_user_id
Validates the lms_user_id, if is given, to see if there is an existing EnterpriseCustomerUser for it.
enterprise/api/v1/serializers.py
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. return models.EnterpriseCustomerUser.objects.get( user_id=value, enterprise_customer=enterprise_customer ) except models.EnterpriseCustomerUser.DoesNotExist: pass return None
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. return models.EnterpriseCustomerUser.objects.get( user_id=value, enterprise_customer=enterprise_customer ) except models.EnterpriseCustomerUser.DoesNotExist: pass return None
[ "Validates", "the", "lms_user_id", "if", "is", "given", "to", "see", "if", "there", "is", "an", "existing", "EnterpriseCustomerUser", "for", "it", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L618-L633
[ "def", "validate_lms_user_id", "(", "self", ",", "value", ")", ":", "enterprise_customer", "=", "self", ".", "context", ".", "get", "(", "'enterprise_customer'", ")", "try", ":", "# Ensure the given user is associated with the enterprise.", "return", "models", ".", "EnterpriseCustomerUser", ".", "objects", ".", "get", "(", "user_id", "=", "value", ",", "enterprise_customer", "=", "enterprise_customer", ")", "except", "models", ".", "EnterpriseCustomerUser", ".", "DoesNotExist", ":", "pass", "return", "None" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnterpriseCustomerCourseEnrollmentsSerializer.validate_tpa_user_id
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/api/v1/serializers.py
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 ) user = User.objects.get(username=username) return models.EnterpriseCustomerUser.objects.get( user_id=user.id, enterprise_customer=enterprise_customer ) except (models.EnterpriseCustomerUser.DoesNotExist, User.DoesNotExist): pass return None
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 ) user = User.objects.get(username=username) return models.EnterpriseCustomerUser.objects.get( user_id=user.id, enterprise_customer=enterprise_customer ) except (models.EnterpriseCustomerUser.DoesNotExist, User.DoesNotExist): pass return None
[ "Validates", "the", "tpa_user_id", "if", "is", "given", "to", "see", "if", "there", "is", "an", "existing", "EnterpriseCustomerUser", "for", "it", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L635-L656
[ "def", "validate_tpa_user_id", "(", "self", ",", "value", ")", ":", "enterprise_customer", "=", "self", ".", "context", ".", "get", "(", "'enterprise_customer'", ")", "try", ":", "tpa_client", "=", "ThirdPartyAuthApiClient", "(", ")", "username", "=", "tpa_client", ".", "get_username_from_remote_id", "(", "enterprise_customer", ".", "identity_provider", ",", "value", ")", "user", "=", "User", ".", "objects", ".", "get", "(", "username", "=", "username", ")", "return", "models", ".", "EnterpriseCustomerUser", ".", "objects", ".", "get", "(", "user_id", "=", "user", ".", "id", ",", "enterprise_customer", "=", "enterprise_customer", ")", "except", "(", "models", ".", "EnterpriseCustomerUser", ".", "DoesNotExist", ",", "User", ".", "DoesNotExist", ")", ":", "pass", "return", "None" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnterpriseCustomerCourseEnrollmentsSerializer.validate_user_email
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/api/v1/serializers.py
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) return models.EnterpriseCustomerUser.objects.get( user_id=user.id, enterprise_customer=enterprise_customer ) except (models.EnterpriseCustomerUser.DoesNotExist, User.DoesNotExist): pass return value
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) return models.EnterpriseCustomerUser.objects.get( user_id=user.id, enterprise_customer=enterprise_customer ) except (models.EnterpriseCustomerUser.DoesNotExist, User.DoesNotExist): pass return value
[ "Validates", "the", "user_email", "if", "given", "to", "see", "if", "an", "existing", "EnterpriseCustomerUser", "exists", "for", "it", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L658-L675
[ "def", "validate_user_email", "(", "self", ",", "value", ")", ":", "enterprise_customer", "=", "self", ".", "context", ".", "get", "(", "'enterprise_customer'", ")", "try", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "email", "=", "value", ")", "return", "models", ".", "EnterpriseCustomerUser", ".", "objects", ".", "get", "(", "user_id", "=", "user", ".", "id", ",", "enterprise_customer", "=", "enterprise_customer", ")", "except", "(", "models", ".", "EnterpriseCustomerUser", ".", "DoesNotExist", ",", "User", ".", "DoesNotExist", ")", ":", "pass", "return", "value" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnterpriseCustomerCourseEnrollmentsSerializer.validate_course_run_id
Validates that the course run id is part of the Enterprise Customer's catalog.
enterprise/api/v1/serializers.py
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 not in the catalog ' 'for Enterprise Customer {enterprise_customer}'.format( course_run_id=value, enterprise_customer=enterprise_customer.name, ) ) return value
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 not in the catalog ' 'for Enterprise Customer {enterprise_customer}'.format( course_run_id=value, enterprise_customer=enterprise_customer.name, ) ) return value
[ "Validates", "that", "the", "course", "run", "id", "is", "part", "of", "the", "Enterprise", "Customer", "s", "catalog", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L677-L692
[ "def", "validate_course_run_id", "(", "self", ",", "value", ")", ":", "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 not in the catalog '", "'for Enterprise Customer {enterprise_customer}'", ".", "format", "(", "course_run_id", "=", "value", ",", "enterprise_customer", "=", "enterprise_customer", ".", "name", ",", ")", ")", "return", "value" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
EnterpriseCustomerCourseEnrollmentsSerializer.validate
Validate that at least one of the user identifier fields has been passed in.
enterprise/api/v1/serializers.py
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: raise serializers.ValidationError( 'At least one of the following fields must be specified and map to an EnterpriseCustomerUser: ' 'lms_user_id, tpa_user_id, user_email' ) return data
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: raise serializers.ValidationError( 'At least one of the following fields must be specified and map to an EnterpriseCustomerUser: ' 'lms_user_id, tpa_user_id, user_email' ) return data
[ "Validate", "that", "at", "least", "one", "of", "the", "user", "identifier", "fields", "has", "been", "passed", "in", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/serializers.py#L694-L707
[ "def", "validate", "(", "self", ",", "data", ")", ":", "# pylint: disable=arguments-differ", "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", ":", "raise", "serializers", ".", "ValidationError", "(", "'At least one of the following fields must be specified and map to an EnterpriseCustomerUser: '", "'lms_user_id, tpa_user_id, user_email'", ")", "return", "data" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
get_paginated_response
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.
enterprise/api/pagination.py
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('?') if data['previous']: previous_page = "{base_url}?{query_parameters}".format( base_url=url, query_parameters=urlparse(data['previous'] or "").query, ) previous_page = previous_page.rstrip('?') return Response(OrderedDict([ ('count', data['count']), ('next', next_page), ('previous', previous_page), ('results', data['results']) ]))
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('?') if data['previous']: previous_page = "{base_url}?{query_parameters}".format( base_url=url, query_parameters=urlparse(data['previous'] or "").query, ) previous_page = previous_page.rstrip('?') return Response(OrderedDict([ ('count', data['count']), ('next', next_page), ('previous', previous_page), ('results', data['results']) ]))
[ "Update", "pagination", "links", "in", "course", "catalog", "data", "and", "return", "DRF", "Response", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/pagination.py#L13-L47
[ "def", "get_paginated_response", "(", "data", ",", "request", ")", ":", "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", "(", "'?'", ")", "if", "data", "[", "'previous'", "]", ":", "previous_page", "=", "\"{base_url}?{query_parameters}\"", ".", "format", "(", "base_url", "=", "url", ",", "query_parameters", "=", "urlparse", "(", "data", "[", "'previous'", "]", "or", "\"\"", ")", ".", "query", ",", ")", "previous_page", "=", "previous_page", ".", "rstrip", "(", "'?'", ")", "return", "Response", "(", "OrderedDict", "(", "[", "(", "'count'", ",", "data", "[", "'count'", "]", ")", ",", "(", "'next'", ",", "next_page", ")", ",", "(", "'previous'", ",", "previous_page", ")", ",", "(", "'results'", ",", "data", "[", "'results'", "]", ")", "]", ")", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
create_switch
Create the `role_based_access_control` switch if it does not already exist.
enterprise/migrations/0067_add_role_based_access_control_switch.py
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})
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})
[ "Create", "the", "role_based_access_control", "switch", "if", "it", "does", "not", "already", "exist", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/migrations/0067_add_role_based_access_control_switch.py#L9-L12
[ "def", "create_switch", "(", "apps", ",", "schema_editor", ")", ":", "Switch", "=", "apps", ".", "get_model", "(", "'waffle'", ",", "'Switch'", ")", "Switch", ".", "objects", ".", "update_or_create", "(", "name", "=", "ENTERPRISE_ROLE_BASED_ACCESS_CONTROL_SWITCH", ",", "defaults", "=", "{", "'active'", ":", "False", "}", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
delete_switch
Delete the `role_based_access_control` switch.
enterprise/migrations/0067_add_role_based_access_control_switch.py
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()
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()
[ "Delete", "the", "role_based_access_control", "switch", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/migrations/0067_add_role_based_access_control_switch.py#L15-L18
[ "def", "delete_switch", "(", "apps", ",", "schema_editor", ")", ":", "Switch", "=", "apps", ".", "get_model", "(", "'waffle'", ",", "'Switch'", ")", "Switch", ".", "objects", ".", "filter", "(", "name", "=", "ENTERPRISE_ROLE_BASED_ACCESS_CONTROL_SWITCH", ")", ".", "delete", "(", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
create_switch
Create and activate the SAP_USE_ENTERPRISE_ENROLLMENT_PAGE switch if it does not already exist.
integrated_channels/sap_success_factors/migrations/0009_sapsuccessfactors_remove_enterprise_enrollment_page_waffle_flag.py
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})
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})
[ "Create", "and", "activate", "the", "SAP_USE_ENTERPRISE_ENROLLMENT_PAGE", "switch", "if", "it", "does", "not", "already", "exist", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/migrations/0009_sapsuccessfactors_remove_enterprise_enrollment_page_waffle_flag.py#L7-L10
[ "def", "create_switch", "(", "apps", ",", "schema_editor", ")", ":", "Switch", "=", "apps", ".", "get_model", "(", "'waffle'", ",", "'Switch'", ")", "Switch", ".", "objects", ".", "get_or_create", "(", "name", "=", "'SAP_USE_ENTERPRISE_ENROLLMENT_PAGE'", ",", "defaults", "=", "{", "'active'", ":", "False", "}", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
SapSuccessFactorsLearnerTransmitter.transmit
Send a completion status call to SAP SuccessFactors using the client. Args: payload: The learner completion data payload to send to SAP SuccessFactors
integrated_channels/sap_success_factors/transmitters/learner_data.py
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_name'] = 'SapSuccessFactorsLearnerDataTransmissionAudit' kwargs['remote_user_id'] = 'sapsf_user_id' super(SapSuccessFactorsLearnerTransmitter, self).transmit(payload, **kwargs)
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_name'] = 'SapSuccessFactorsLearnerDataTransmissionAudit' kwargs['remote_user_id'] = 'sapsf_user_id' super(SapSuccessFactorsLearnerTransmitter, self).transmit(payload, **kwargs)
[ "Send", "a", "completion", "status", "call", "to", "SAP", "SuccessFactors", "using", "the", "client", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/transmitters/learner_data.py#L32-L42
[ "def", "transmit", "(", "self", ",", "payload", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'app_label'", "]", "=", "'sap_success_factors'", "kwargs", "[", "'model_name'", "]", "=", "'SapSuccessFactorsLearnerDataTransmissionAudit'", "kwargs", "[", "'remote_user_id'", "]", "=", "'sapsf_user_id'", "super", "(", "SapSuccessFactorsLearnerTransmitter", ",", "self", ")", ".", "transmit", "(", "payload", ",", "*", "*", "kwargs", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
SapSuccessFactorsLearnerTransmitter.handle_transmission_error
Handle the case where the employee on SAPSF's side is marked as inactive.
integrated_channels/sap_success_factors/transmitters/learner_data.py
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 is inactive' in sys_msg: ecu = EnterpriseCustomerUser.objects.get( enterprise_enrollments__id=learner_data.enterprise_course_enrollment_id) ecu.active = False ecu.save() LOGGER.warning( 'User %s with ID %s and email %s is a former employee of %s ' 'and has been marked inactive in SAPSF. Now marking inactive internally.', ecu.username, ecu.user_id, ecu.user_email, ecu.enterprise_customer ) return super(SapSuccessFactorsLearnerTransmitter, self).handle_transmission_error(learner_data, request_exception)
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 is inactive' in sys_msg: ecu = EnterpriseCustomerUser.objects.get( enterprise_enrollments__id=learner_data.enterprise_course_enrollment_id) ecu.active = False ecu.save() LOGGER.warning( 'User %s with ID %s and email %s is a former employee of %s ' 'and has been marked inactive in SAPSF. Now marking inactive internally.', ecu.username, ecu.user_id, ecu.user_email, ecu.enterprise_customer ) return super(SapSuccessFactorsLearnerTransmitter, self).handle_transmission_error(learner_data, request_exception)
[ "Handle", "the", "case", "where", "the", "employee", "on", "SAPSF", "s", "side", "is", "marked", "as", "inactive", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/integrated_channels/sap_success_factors/transmitters/learner_data.py#L44-L62
[ "def", "handle_transmission_error", "(", "self", ",", "learner_data", ",", "request_exception", ")", ":", "try", ":", "sys_msg", "=", "request_exception", ".", "response", ".", "content", "except", "AttributeError", ":", "pass", "else", ":", "if", "'user account is inactive'", "in", "sys_msg", ":", "ecu", "=", "EnterpriseCustomerUser", ".", "objects", ".", "get", "(", "enterprise_enrollments__id", "=", "learner_data", ".", "enterprise_course_enrollment_id", ")", "ecu", ".", "active", "=", "False", "ecu", ".", "save", "(", ")", "LOGGER", ".", "warning", "(", "'User %s with ID %s and email %s is a former employee of %s '", "'and has been marked inactive in SAPSF. Now marking inactive internally.'", ",", "ecu", ".", "username", ",", "ecu", ".", "user_id", ",", "ecu", ".", "user_email", ",", "ecu", ".", "enterprise_customer", ")", "return", "super", "(", "SapSuccessFactorsLearnerTransmitter", ",", "self", ")", ".", "handle_transmission_error", "(", "learner_data", ",", "request_exception", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80
valid
ServiceUserThrottle.allow_request
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` key in `REST_FRAMEWORK` setting. service user throttling is specified in `DEFAULT_THROTTLE_RATES` by `service_user` key Example Setting: ``` REST_FRAMEWORK = { ... 'DEFAULT_THROTTLE_RATES': { ... 'service_user': '50/day' } } ```
enterprise/api/throttles.py
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` key in `REST_FRAMEWORK` setting. service user throttling is specified in `DEFAULT_THROTTLE_RATES` by `service_user` key Example Setting: ``` REST_FRAMEWORK = { ... 'DEFAULT_THROTTLE_RATES': { ... 'service_user': '50/day' } } ``` """ service_users = get_service_usernames() # User service user throttling rates for service user. if request.user.username in service_users: self.update_throttle_scope() return super(ServiceUserThrottle, self).allow_request(request, view)
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` key in `REST_FRAMEWORK` setting. service user throttling is specified in `DEFAULT_THROTTLE_RATES` by `service_user` key Example Setting: ``` REST_FRAMEWORK = { ... 'DEFAULT_THROTTLE_RATES': { ... 'service_user': '50/day' } } ``` """ service_users = get_service_usernames() # User service user throttling rates for service user. if request.user.username in service_users: self.update_throttle_scope() return super(ServiceUserThrottle, self).allow_request(request, view)
[ "Modify", "throttling", "for", "service", "users", "." ]
edx/edx-enterprise
python
https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/throttles.py#L19-L46
[ "def", "allow_request", "(", "self", ",", "request", ",", "view", ")", ":", "service_users", "=", "get_service_usernames", "(", ")", "# User service user throttling rates for service user.", "if", "request", ".", "user", ".", "username", "in", "service_users", ":", "self", ".", "update_throttle_scope", "(", ")", "return", "super", "(", "ServiceUserThrottle", ",", "self", ")", ".", "allow_request", "(", "request", ",", "view", ")" ]
aea91379ab0a87cd3bc798961fce28b60ee49a80