Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
HeaderIdProcessor._unique_id
(self, id)
Ensure ID is unique. Append '_1', '_2'... if not
Ensure ID is unique. Append '_1', '_2'... if not
def _unique_id(self, id): """ Ensure ID is unique. Append '_1', '_2'... if not """ while id in self.IDs: m = IDCOUNT_RE.match(id) if m: id = '%s_%d'% (m.group(1), int(m.group(2))+1) else: id = '%s_%d'% (id, 1) self.IDs.append(id...
[ "def", "_unique_id", "(", "self", ",", "id", ")", ":", "while", "id", "in", "self", ".", "IDs", ":", "m", "=", "IDCOUNT_RE", ".", "match", "(", "id", ")", "if", "m", ":", "id", "=", "'%s_%d'", "%", "(", "m", ".", "group", "(", "1", ")", ",", ...
[ 143, 4 ]
[ 152, 17 ]
python
en
['en', 'en', 'en']
True
HeaderIdProcessor._create_id
(self, header)
Return ID from Header text.
Return ID from Header text.
def _create_id(self, header): """ Return ID from Header text. """ h = '' for c in header.lower().replace(' ', '_'): if c in ID_CHARS: h += c elif c not in punctuation: h += '+' return self._unique_id(h)
[ "def", "_create_id", "(", "self", ",", "header", ")", ":", "h", "=", "''", "for", "c", "in", "header", ".", "lower", "(", ")", ".", "replace", "(", "' '", ",", "'_'", ")", ":", "if", "c", "in", "ID_CHARS", ":", "h", "+=", "c", "elif", "c", "n...
[ 154, 4 ]
[ 162, 33 ]
python
en
['en', 'en', 'en']
True
parse_anchor_value
(anchor_val: Optional[str], use_first_unread_anchor: bool)
Given the anchor and use_first_unread_anchor parameters passed by the client, computes what anchor value the client requested, handling backwards-compatibility and the various string-valued fields. We encode use_first_unread_anchor as anchor=None.
Given the anchor and use_first_unread_anchor parameters passed by the client, computes what anchor value the client requested, handling backwards-compatibility and the various string-valued fields. We encode use_first_unread_anchor as anchor=None.
def parse_anchor_value(anchor_val: Optional[str], use_first_unread_anchor: bool) -> Optional[int]: """Given the anchor and use_first_unread_anchor parameters passed by the client, computes what anchor value the client requested, handling backwards-compatibility and the various string-valued fields. We ...
[ "def", "parse_anchor_value", "(", "anchor_val", ":", "Optional", "[", "str", "]", ",", "use_first_unread_anchor", ":", "bool", ")", "->", "Optional", "[", "int", "]", ":", "if", "use_first_unread_anchor", ":", "# Backwards-compatibility: Before we added support for the"...
[ 894, 0 ]
[ 929, 48 ]
python
en
['en', 'en', 'en']
True
limit_query_to_range
( query: Select, num_before: int, num_after: int, anchor: int, anchored_to_left: bool, anchored_to_right: bool, id_col: "ColumnElement[int]", first_visible_message_id: int, )
This code is actually generic enough that we could move it to a library, but our only caller for now is message search.
This code is actually generic enough that we could move it to a library, but our only caller for now is message search.
def limit_query_to_range( query: Select, num_before: int, num_after: int, anchor: int, anchored_to_left: bool, anchored_to_right: bool, id_col: "ColumnElement[int]", first_visible_message_id: int, ) -> FromClause: """ This code is actually generic enough that we could move it to ...
[ "def", "limit_query_to_range", "(", "query", ":", "Select", ",", "num_before", ":", "int", ",", "num_after", ":", "int", ",", "anchor", ":", "int", ",", "anchored_to_left", ":", "bool", ",", "anchored_to_right", ":", "bool", ",", "id_col", ":", "\"ColumnElem...
[ 1160, 0 ]
[ 1238, 44 ]
python
en
['en', 'error', 'th']
False
NarrowBuilder.add_term
(self, query: Select, term: Dict[str, Any])
Extend the given query to one narrowed by the given term, and return the result. This method satisfies an important security property: the returned query never includes a message that the given query didn't. In particular, if the given query will only find messages that a given ...
Extend the given query to one narrowed by the given term, and return the result.
def add_term(self, query: Select, term: Dict[str, Any]) -> Select: """ Extend the given query to one narrowed by the given term, and return the result. This method satisfies an important security property: the returned query never includes a message that the given query didn't. In ...
[ "def", "add_term", "(", "self", ",", "query", ":", "Select", ",", "term", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Select", ":", "# To maintain the security property, we hold all the `by_*`", "# methods to the same criterion. See the class's block comment", ...
[ 161, 4 ]
[ 192, 51 ]
python
en
['en', 'error', 'th']
False
NarrowBuilder._pg_re_escape
(self, pattern: str)
Escape user input to place in a regex Python's re.escape escapes Unicode characters in a way which PostgreSQL fails on, '\u03bb' to '\\\u03bb'. This function will correctly escape them for PostgreSQL, '\u03bb' to '\\u03bb'.
Escape user input to place in a regex
def _pg_re_escape(self, pattern: str) -> str: """ Escape user input to place in a regex Python's re.escape escapes Unicode characters in a way which PostgreSQL fails on, '\u03bb' to '\\\u03bb'. This function will correctly escape them for PostgreSQL, '\u03bb' to '\\u03bb'. ...
[ "def", "_pg_re_escape", "(", "self", ",", "pattern", ":", "str", ")", "->", "str", ":", "s", "=", "list", "(", "pattern", ")", "for", "i", ",", "c", "in", "enumerate", "(", "s", ")", ":", "if", "c", "not", "in", "self", ".", "_alphanum", ":", "...
[ 240, 4 ]
[ 257, 25 ]
python
en
['en', 'error', 'th']
False
RPC.method
(self, method)
Get the document root. For I{rpc/(literal|encoded)}, this is the name of the method qualifed by the schema tns. @param method: A service method. @type method: I{service.Method} @return: A root element. @rtype: L{Element}
Get the document root. For I{rpc/(literal|encoded)}, this is the name of the method qualifed by the schema tns.
def method(self, method): """ Get the document root. For I{rpc/(literal|encoded)}, this is the name of the method qualifed by the schema tns. @param method: A service method. @type method: I{service.Method} @return: A root element. @rtype: L{Element} """ ...
[ "def", "method", "(", "self", ",", "method", ")", ":", "ns", "=", "method", ".", "soap", ".", "input", ".", "body", ".", "namespace", "if", "ns", "[", "0", "]", "is", "None", ":", "ns", "=", "(", "'ns0'", ",", "ns", "[", "1", "]", ")", "metho...
[ 64, 4 ]
[ 77, 21 ]
python
en
['en', 'error', 'th']
False
Encoded.unmarshaller
(self, typed=True)
Get the appropriate XML decoder. @return: Either the (basic|typed) unmarshaller. @rtype: L{UmxTyped}
Get the appropriate XML decoder.
def unmarshaller(self, typed=True): """ Get the appropriate XML decoder. @return: Either the (basic|typed) unmarshaller. @rtype: L{UmxTyped} """ if typed: return UmxEncoded(self.schema()) else: return RPC.unmarshaller(self, typed)
[ "def", "unmarshaller", "(", "self", ",", "typed", "=", "True", ")", ":", "if", "typed", ":", "return", "UmxEncoded", "(", "self", ".", "schema", "(", ")", ")", "else", ":", "return", "RPC", ".", "unmarshaller", "(", "self", ",", "typed", ")" ]
[ 88, 4 ]
[ 97, 48 ]
python
en
['en', 'error', 'th']
False
copy
(x)
Shallow copy operation on arbitrary Python objects. See the module's __doc__ string for more info.
Shallow copy operation on arbitrary Python objects.
def copy(x): """Shallow copy operation on arbitrary Python objects. See the module's __doc__ string for more info. """ cls = type(x) copier = _copy_dispatch.get(cls) if copier: return copier(x) try: issc = issubclass(cls, type) except TypeError: # cls is not a class ...
[ "def", "copy", "(", "x", ")", ":", "cls", "=", "type", "(", "x", ")", "copier", "=", "_copy_dispatch", ".", "get", "(", "cls", ")", "if", "copier", ":", "return", "copier", "(", "x", ")", "try", ":", "issc", "=", "issubclass", "(", "cls", ",", ...
[ 65, 0 ]
[ 105, 37 ]
python
en
['en', 'mg', 'en']
True
deepcopy
(x, memo=None, _nil=[])
Deep copy operation on arbitrary Python objects. See the module's __doc__ string for more info.
Deep copy operation on arbitrary Python objects.
def deepcopy(x, memo=None, _nil=[]): """Deep copy operation on arbitrary Python objects. See the module's __doc__ string for more info. """ if memo is None: memo = {} d = id(x) y = memo.get(d, _nil) if y is not _nil: return y cls = type(x) copier = _deepcopy_disp...
[ "def", "deepcopy", "(", "x", ",", "memo", "=", "None", ",", "_nil", "=", "[", "]", ")", ":", "if", "memo", "is", "None", ":", "memo", "=", "{", "}", "d", "=", "id", "(", "x", ")", "y", "=", "memo", ".", "get", "(", "d", ",", "_nil", ")", ...
[ 131, 0 ]
[ 185, 12 ]
python
en
['en', 'mg', 'en']
True
_keep_alive
(x, memo)
Keeps a reference to the object x in the memo. Because we remember objects by their id, we have to assure that possibly temporary objects are kept alive by referencing them. We store a reference at the id of the memo, which should normally not be used unless someone tries to deepcopy the memo i...
Keeps a reference to the object x in the memo.
def _keep_alive(x, memo): """Keeps a reference to the object x in the memo. Because we remember objects by their id, we have to assure that possibly temporary objects are kept alive by referencing them. We store a reference at the id of the memo, which should normally not be used unless someone...
[ "def", "_keep_alive", "(", "x", ",", "memo", ")", ":", "try", ":", "memo", "[", "id", "(", "memo", ")", "]", ".", "append", "(", "x", ")", "except", "KeyError", ":", "# aha, this is the first one :-)", "memo", "[", "id", "(", "memo", ")", "]", "=", ...
[ 251, 0 ]
[ 265, 26 ]
python
en
['en', 'en', 'en']
True
login
(request)
Logs a user in using the :class:`~openstack_auth.forms.Login` form.
Logs a user in using the :class:`~openstack_auth.forms.Login` form.
def login(request): """Logs a user in using the :class:`~openstack_auth.forms.Login` form.""" # If the user enabled websso and the default redirect # redirect to the default websso url if (request.method == 'GET' and utils.is_websso_enabled and utils.is_websso_default_redirect()): p...
[ "def", "login", "(", "request", ")", ":", "# If the user enabled websso and the default redirect", "# redirect to the default websso url", "if", "(", "request", ".", "method", "==", "'GET'", "and", "utils", ".", "is_websso_enabled", "and", "utils", ".", "is_websso_default...
[ 54, 0 ]
[ 157, 14 ]
python
en
['en', 'en', 'en']
True
websso
(request)
Logs a user in using a token from Keystone's POST.
Logs a user in using a token from Keystone's POST.
def websso(request): """Logs a user in using a token from Keystone's POST.""" auth_url = settings.OPENSTACK_KEYSTONE_URL token = request.POST.get('token') try: request.user = auth.authenticate(request, auth_url=auth_url, token=token) except exceptions...
[ "def", "websso", "(", "request", ")", ":", "auth_url", "=", "settings", ".", "OPENSTACK_KEYSTONE_URL", "token", "=", "request", ".", "POST", ".", "get", "(", "'token'", ")", "try", ":", "request", ".", "user", "=", "auth", ".", "authenticate", "(", "requ...
[ 164, 0 ]
[ 189, 56 ]
python
en
['en', 'en', 'en']
True
logout
(request, login_url=None, **kwargs)
Logs out the user if he is logged in. Then redirects to the log-in page. :param login_url: Once logged out, defines the URL where to redirect after login :param kwargs: see django.contrib.auth.views.logout_then_login extra parameters.
Logs out the user if he is logged in. Then redirects to the log-in page.
def logout(request, login_url=None, **kwargs): """Logs out the user if he is logged in. Then redirects to the log-in page. :param login_url: Once logged out, defines the URL where to redirect after login :param kwargs: see django.contrib.auth.views.logout_then_login extra parameters. ...
[ "def", "logout", "(", "request", ",", "login_url", "=", "None", ",", "*", "*", "kwargs", ")", ":", "msg", "=", "'Logging out user \"%(username)s\".'", "%", "{", "'username'", ":", "request", ".", "user", ".", "username", "}", "LOG", ".", "info", "(", "ms...
[ 193, 0 ]
[ 216, 60 ]
python
en
['en', 'en', 'en']
True
switch
(request, tenant_id, redirect_field_name=auth.REDIRECT_FIELD_NAME)
Switches an authenticated user from one project to another.
Switches an authenticated user from one project to another.
def switch(request, tenant_id, redirect_field_name=auth.REDIRECT_FIELD_NAME): """Switches an authenticated user from one project to another.""" LOG.debug('Switching to tenant %s for user "%s".', tenant_id, request.user.username) endpoint, __ = utils.fix_auth_url_version_prefix(request.user.en...
[ "def", "switch", "(", "request", ",", "tenant_id", ",", "redirect_field_name", "=", "auth", ".", "REDIRECT_FIELD_NAME", ")", ":", "LOG", ".", "debug", "(", "'Switching to tenant %s for user \"%s\".'", ",", "tenant_id", ",", "request", ".", "user", ".", "username",...
[ 221, 0 ]
[ 269, 19 ]
python
en
['en', 'en', 'en']
True
switch_region
(request, region_name, redirect_field_name=auth.REDIRECT_FIELD_NAME)
Switches the user's region for all services except Identity service. The region will be switched if the given region is one of the regions available for the scoped project. Otherwise the region is not switched.
Switches the user's region for all services except Identity service.
def switch_region(request, region_name, redirect_field_name=auth.REDIRECT_FIELD_NAME): """Switches the user's region for all services except Identity service. The region will be switched if the given region is one of the regions available for the scoped project. Otherwise the region is no...
[ "def", "switch_region", "(", "request", ",", "region_name", ",", "redirect_field_name", "=", "auth", ".", "REDIRECT_FIELD_NAME", ")", ":", "if", "region_name", "in", "request", ".", "user", ".", "available_services_regions", ":", "request", ".", "session", "[", ...
[ 274, 0 ]
[ 294, 19 ]
python
en
['en', 'en', 'en']
True
switch_keystone_provider
(request, keystone_provider=None, redirect_field_name=auth.REDIRECT_FIELD_NAME)
Switches the user's keystone provider using K2K Federation If keystone_provider is given then we switch the user to the keystone provider using K2K federation. Otherwise if keystone_provider is None then we switch the user back to the Identity Provider Keystone which a non federated token auth will be ...
Switches the user's keystone provider using K2K Federation
def switch_keystone_provider(request, keystone_provider=None, redirect_field_name=auth.REDIRECT_FIELD_NAME): """Switches the user's keystone provider using K2K Federation If keystone_provider is given then we switch the user to the keystone provider using K2K federation. Otherw...
[ "def", "switch_keystone_provider", "(", "request", ",", "keystone_provider", "=", "None", ",", "redirect_field_name", "=", "auth", ".", "REDIRECT_FIELD_NAME", ")", ":", "base_token", "=", "request", ".", "session", ".", "get", "(", "'k2k_base_unscoped_token'", ",", ...
[ 299, 0 ]
[ 368, 19 ]
python
en
['en', 'en', 'en']
True
Factory.maptag
(cls, tag, fn)
Map (override) tag => I{class} mapping. @param tag: An xsd tag name. @type tag: str @param fn: A function or class. @type fn: fn|class.
Map (override) tag => I{class} mapping.
def maptag(cls, tag, fn): """ Map (override) tag => I{class} mapping. @param tag: An xsd tag name. @type tag: str @param fn: A function or class. @type fn: fn|class. """ cls.tags[tag] = fn
[ "def", "maptag", "(", "cls", ",", "tag", ",", "fn", ")", ":", "cls", ".", "tags", "[", "tag", "]", "=", "fn" ]
[ 248, 4 ]
[ 256, 26 ]
python
en
['en', 'error', 'th']
False
Factory.create
(cls, schema, name)
Create an object based on the root tag name. @param schema: A schema object. @type schema: L{schema.Schema} @param name: The name. @type name: str @return: The created object. @rtype: L{XBuiltin}
Create an object based on the root tag name.
def create(cls, schema, name): """ Create an object based on the root tag name. @param schema: A schema object. @type schema: L{schema.Schema} @param name: The name. @type name: str @return: The created object. @rtype: L{XBuiltin} """ fn =...
[ "def", "create", "(", "cls", ",", "schema", ",", "name", ")", ":", "fn", "=", "cls", ".", "tags", ".", "get", "(", "name", ")", "if", "fn", "is", "not", "None", ":", "return", "fn", "(", "schema", ",", "name", ")", "else", ":", "return", "XBuil...
[ 259, 4 ]
[ 273, 41 ]
python
en
['en', 'error', 'th']
False
ConfigurationCommand.list_config_values
(self, options, args)
List config key-value pairs across different config files
List config key-value pairs across different config files
def list_config_values(self, options, args): # type: (Values, List[str]) -> None """List config key-value pairs across different config files""" self._get_n_args(args, "debug", n=0) self.print_env_var_values() # Iterate over config files and print if they exist, and the ...
[ "def", "list_config_values", "(", "self", ",", "options", ",", "args", ")", ":", "# type: (Values, List[str]) -> None", "self", ".", "_get_n_args", "(", "args", ",", "\"debug\"", ",", "n", "=", "0", ")", "self", ".", "print_env_var_values", "(", ")", "# Iterat...
[ 195, 4 ]
[ 211, 62 ]
python
en
['fr', 'en', 'en']
True
ConfigurationCommand.print_config_file_values
(self, variant)
Get key-value pairs from the file of a variant
Get key-value pairs from the file of a variant
def print_config_file_values(self, variant): # type: (Kind) -> None """Get key-value pairs from the file of a variant""" for name, value in self.configuration.\ get_values_in_config(variant).items(): with indent_log(): write_output("%s: %s", name, valu...
[ "def", "print_config_file_values", "(", "self", ",", "variant", ")", ":", "# type: (Kind) -> None", "for", "name", ",", "value", "in", "self", ".", "configuration", ".", "get_values_in_config", "(", "variant", ")", ".", "items", "(", ")", ":", "with", "indent_...
[ 213, 4 ]
[ 219, 51 ]
python
en
['en', 'en', 'en']
True
ConfigurationCommand.print_env_var_values
(self)
Get key-values pairs present as environment variables
Get key-values pairs present as environment variables
def print_env_var_values(self): # type: () -> None """Get key-values pairs present as environment variables""" write_output("%s:", 'env_var') with indent_log(): for key, value in sorted(self.configuration.get_environ_vars()): env_var = 'PIP_{}'.format(key.uppe...
[ "def", "print_env_var_values", "(", "self", ")", ":", "# type: () -> None", "write_output", "(", "\"%s:\"", ",", "'env_var'", ")", "with", "indent_log", "(", ")", ":", "for", "key", ",", "value", "in", "sorted", "(", "self", ".", "configuration", ".", "get_e...
[ 221, 4 ]
[ 228, 53 ]
python
en
['fr', 'en', 'en']
True
ConfigurationCommand._get_n_args
(self, args, example, n)
Helper to make sure the command got the right number of arguments
Helper to make sure the command got the right number of arguments
def _get_n_args(self, args, example, n): # type: (List[str], str, int) -> Any """Helper to make sure the command got the right number of arguments """ if len(args) != n: msg = ( 'Got unexpected number of arguments, expected {}. ' '(example: "{}...
[ "def", "_get_n_args", "(", "self", ",", "args", ",", "example", ",", "n", ")", ":", "# type: (List[str], str, int) -> Any", "if", "len", "(", "args", ")", "!=", "n", ":", "msg", "=", "(", "'Got unexpected number of arguments, expected {}. '", "'(example: \"{} config...
[ 246, 4 ]
[ 260, 23 ]
python
en
['en', 'en', 'en']
True
warn
(msg)
print warning message
print warning message
def warn(msg): ''' print warning message ''' prog = os.path.basename(sys.argv[0]) print('{prog}: warning: {msg}'.format(prog=prog, msg=msg), file=sys.stderr)
[ "def", "warn", "(", "msg", ")", ":", "prog", "=", "os", ".", "path", ".", "basename", "(", "sys", ".", "argv", "[", "0", "]", ")", "print", "(", "'{prog}: warning: {msg}'", ".", "format", "(", "prog", "=", "prog", ",", "msg", "=", "msg", ")", ","...
[ 27, 0 ]
[ 32, 79 ]
python
en
['en', 'error', 'th']
False
_coerce_case
(src, word)
coerce word to the same case as src (simple version doesn't support title-case)
coerce word to the same case as src (simple version doesn't support title-case)
def _coerce_case(src, word): ''' coerce word to the same case as src (simple version doesn't support title-case) ''' if src.isupper(): return word.upper() else: return word.lower()
[ "def", "_coerce_case", "(", "src", ",", "word", ")", ":", "if", "src", ".", "isupper", "(", ")", ":", "return", "word", ".", "upper", "(", ")", "else", ":", "return", "word", ".", "lower", "(", ")" ]
[ 34, 0 ]
[ 42, 27 ]
python
en
['en', 'error', 'th']
False
coerce_case
(src, word)
coerce word to the same case as src
coerce word to the same case as src
def coerce_case(src, word): ''' coerce word to the same case as src ''' return ( _coerce_case(src[:1], word[:1]) + _coerce_case(src[1:], word[1:]) )
[ "def", "coerce_case", "(", "src", ",", "word", ")", ":", "return", "(", "_coerce_case", "(", "src", "[", ":", "1", "]", ",", "word", "[", ":", "1", "]", ")", "+", "_coerce_case", "(", "src", "[", "1", ":", "]", ",", "word", "[", "1", ":", "]"...
[ 44, 0 ]
[ 51, 5 ]
python
en
['en', 'error', 'th']
False
make_raw
(query: Any, exclude: Optional[List[Field]] = None)
Takes a Django query and returns a JSONable list of dictionaries corresponding to the database rows.
Takes a Django query and returns a JSONable list of dictionaries corresponding to the database rows.
def make_raw(query: Any, exclude: Optional[List[Field]] = None) -> List[Record]: """ Takes a Django query and returns a JSONable list of dictionaries corresponding to the database rows. """ rows = [] for instance in query: data = model_to_dict(instance, exclude=exclude) """ ...
[ "def", "make_raw", "(", "query", ":", "Any", ",", "exclude", ":", "Optional", "[", "List", "[", "Field", "]", "]", "=", "None", ")", "->", "List", "[", "Record", "]", ":", "rows", "=", "[", "]", "for", "instance", "in", "query", ":", "data", "=",...
[ 347, 0 ]
[ 367, 15 ]
python
en
['en', 'error', 'th']
False
fetch_attachment_data
(response: TableData, realm_id: int, message_ids: Set[int])
We usually export most messages for the realm, but not quite ALL messages for the realm. So, we need to clean up our attachment data to have correct values for response['zerver_attachment'][<n>]['messages'].
We usually export most messages for the realm, but not quite ALL messages for the realm. So, we need to clean up our attachment data to have correct values for response['zerver_attachment'][<n>]['messages'].
def fetch_attachment_data(response: TableData, realm_id: int, message_ids: Set[int]) -> None: filter_args = {"realm_id": realm_id} query = Attachment.objects.filter(**filter_args) response["zerver_attachment"] = make_raw(list(query)) floatify_datetime_fields(response, "zerver_attachment") """ W...
[ "def", "fetch_attachment_data", "(", "response", ":", "TableData", ",", "realm_id", ":", "int", ",", "message_ids", ":", "Set", "[", "int", "]", ")", "->", "None", ":", "filter_args", "=", "{", "\"realm_id\"", ":", "realm_id", "}", "query", "=", "Attachmen...
[ 909, 0 ]
[ 934, 5 ]
python
en
['en', 'error', 'th']
False
export_usermessages_batch
( input_path: Path, output_path: Path, consent_message_id: Optional[int] = None )
As part of the system for doing parallel exports, this runs on one batch of Message objects and adds the corresponding UserMessage objects. (This is called by the export_usermessage_batch management command).
As part of the system for doing parallel exports, this runs on one batch of Message objects and adds the corresponding UserMessage objects. (This is called by the export_usermessage_batch management command).
def export_usermessages_batch( input_path: Path, output_path: Path, consent_message_id: Optional[int] = None ) -> None: """As part of the system for doing parallel exports, this runs on one batch of Message objects and adds the corresponding UserMessage objects. (This is called by the export_usermessage...
[ "def", "export_usermessages_batch", "(", "input_path", ":", "Path", ",", "output_path", ":", "Path", ",", "consent_message_id", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "None", ":", "with", "open", "(", "input_path", ",", "\"rb\"", ")", "a...
[ 1011, 0 ]
[ 1029, 25 ]
python
en
['en', 'en', 'en']
True
getfixturemarker
(obj)
return fixturemarker or None if it doesn't exist or raised exceptions.
return fixturemarker or None if it doesn't exist or raised exceptions.
def getfixturemarker(obj): """ return fixturemarker or None if it doesn't exist or raised exceptions.""" try: return getattr(obj, "_pytestfixturefunction", None) except TEST_OUTCOME: # some objects raise errors like request (from flask import request) # we don't expect them to be...
[ "def", "getfixturemarker", "(", "obj", ")", ":", "try", ":", "return", "getattr", "(", "obj", ",", "\"_pytestfixturefunction\"", ",", "None", ")", "except", "TEST_OUTCOME", ":", "# some objects raise errors like request (from flask import request)", "# we don't expect them ...
[ 129, 0 ]
[ 137, 19 ]
python
en
['en', 'en', 'en']
True
get_parametrized_fixture_keys
(item, scopenum)
return list of keys for all parametrized arguments which match the specified scope.
return list of keys for all parametrized arguments which match the specified scope.
def get_parametrized_fixture_keys(item, scopenum): """ return list of keys for all parametrized arguments which match the specified scope. """ assert scopenum < scopenum_function # function try: cs = item.callspec except AttributeError: pass else: # cs.indices.items() is...
[ "def", "get_parametrized_fixture_keys", "(", "item", ",", "scopenum", ")", ":", "assert", "scopenum", "<", "scopenum_function", "# function", "try", ":", "cs", "=", "item", ".", "callspec", "except", "AttributeError", ":", "pass", "else", ":", "# cs.indices.items(...
[ 140, 0 ]
[ 161, 21 ]
python
en
['en', 'en', 'en']
True
fillfixtures
(function)
fill missing funcargs for a test function.
fill missing funcargs for a test function.
def fillfixtures(function): """ fill missing funcargs for a test function. """ try: request = function._request except AttributeError: # XXX this special code path is only expected to execute # with the oejskit plugin. It uses classes with funcargs # and we thus have to work...
[ "def", "fillfixtures", "(", "function", ")", ":", "try", ":", "request", "=", "function", ".", "_request", "except", "AttributeError", ":", "# XXX this special code path is only expected to execute", "# with the oejskit plugin. It uses classes with funcargs", "# and we thus have...
[ 226, 0 ]
[ 245, 31 ]
python
en
['en', 'en', 'en']
True
scope2index
(scope, descr, where=None)
Look up the index of ``scope`` and raise a descriptive value error if not defined.
Look up the index of ``scope`` and raise a descriptive value error if not defined.
def scope2index(scope, descr, where=None): """Look up the index of ``scope`` and raise a descriptive value error if not defined. """ try: return scopes.index(scope) except ValueError: raise ValueError( "{0} {1}has an unsupported scope value '{2}'".format( ...
[ "def", "scope2index", "(", "scope", ",", "descr", ",", "where", "=", "None", ")", ":", "try", ":", "return", "scopes", ".", "index", "(", "scope", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"{0} {1}has an unsupported scope value '{2}'\"", ...
[ 608, 0 ]
[ 619, 9 ]
python
en
['en', 'en', 'en']
True
pytest_fixture_setup
(fixturedef, request)
Execution of fixture setup.
Execution of fixture setup.
def pytest_fixture_setup(fixturedef, request): """ Execution of fixture setup. """ kwargs = {} for argname in fixturedef.argnames: fixdef = request._get_active_fixturedef(argname) result, arg_cache_key, exc = fixdef.cached_result request._check_scope(argname, request.scope, fixdef.sc...
[ "def", "pytest_fixture_setup", "(", "fixturedef", ",", "request", ")", ":", "kwargs", "=", "{", "}", "for", "argname", "in", "fixturedef", ".", "argnames", ":", "fixdef", "=", "request", ".", "_get_active_fixturedef", "(", "argname", ")", "result", ",", "arg...
[ 803, 0 ]
[ 832, 17 ]
python
en
['en', 'su', 'en']
True
fixture
(scope="function", params=None, autouse=False, ids=None, name=None)
(return a) decorator to mark a fixture factory function. This decorator can be used (with or without parameters) to define a fixture function. The name of the fixture function can later be referenced to cause its invocation ahead of running tests: test modules or classes can use the pytest.mark.usefi...
(return a) decorator to mark a fixture factory function.
def fixture(scope="function", params=None, autouse=False, ids=None, name=None): """ (return a) decorator to mark a fixture factory function. This decorator can be used (with or without parameters) to define a fixture function. The name of the fixture function can later be referenced to cause its invoc...
[ "def", "fixture", "(", "scope", "=", "\"function\"", ",", "params", "=", "None", ",", "autouse", "=", "False", ",", "ids", "=", "None", ",", "name", "=", "None", ")", ":", "if", "callable", "(", "scope", ")", "and", "params", "is", "None", "and", "...
[ 859, 0 ]
[ 903, 76 ]
python
en
['en', 'en', 'en']
True
yield_fixture
(scope="function", params=None, autouse=False, ids=None, name=None)
(return a) decorator to mark a yield-fixture factory function. .. deprecated:: 3.0 Use :py:func:`pytest.fixture` directly instead.
(return a) decorator to mark a yield-fixture factory function.
def yield_fixture(scope="function", params=None, autouse=False, ids=None, name=None): """ (return a) decorator to mark a yield-fixture factory function. .. deprecated:: 3.0 Use :py:func:`pytest.fixture` directly instead. """ if callable(scope) and params is None and not autouse: # direc...
[ "def", "yield_fixture", "(", "scope", "=", "\"function\"", ",", "params", "=", "None", ",", "autouse", "=", "False", ",", "ids", "=", "None", ",", "name", "=", "None", ")", ":", "if", "callable", "(", "scope", ")", "and", "params", "is", "None", "and...
[ 906, 0 ]
[ 917, 80 ]
python
en
['en', 'en', 'en']
True
pytestconfig
(request)
the pytest config object with access to command line opts.
the pytest config object with access to command line opts.
def pytestconfig(request): """ the pytest config object with access to command line opts.""" return request.config
[ "def", "pytestconfig", "(", "request", ")", ":", "return", "request", ".", "config" ]
[ 924, 0 ]
[ 926, 25 ]
python
en
['en', 'en', 'en']
True
FixtureRequest.node
(self)
underlying collection node (depends on current request scope)
underlying collection node (depends on current request scope)
def node(self): """ underlying collection node (depends on current request scope)""" return self._getscopeitem(self.scope)
[ "def", "node", "(", "self", ")", ":", "return", "self", ".", "_getscopeitem", "(", "self", ".", "scope", ")" ]
[ 285, 4 ]
[ 287, 45 ]
python
en
['en', 'en', 'en']
True
FixtureRequest.config
(self)
the pytest config object associated with this request.
the pytest config object associated with this request.
def config(self): """ the pytest config object associated with this request. """ return self._pyfuncitem.config
[ "def", "config", "(", "self", ")", ":", "return", "self", ".", "_pyfuncitem", ".", "config" ]
[ 306, 4 ]
[ 308, 38 ]
python
en
['en', 'en', 'en']
True
FixtureRequest.function
(self)
test function object if the request has a per-function scope.
test function object if the request has a per-function scope.
def function(self): """ test function object if the request has a per-function scope. """ return self._pyfuncitem.obj
[ "def", "function", "(", "self", ")", ":", "return", "self", ".", "_pyfuncitem", ".", "obj" ]
[ 311, 4 ]
[ 313, 35 ]
python
en
['en', 'en', 'en']
True
FixtureRequest.cls
(self)
class (can be None) where the test function was collected.
class (can be None) where the test function was collected.
def cls(self): """ class (can be None) where the test function was collected. """ clscol = self._pyfuncitem.getparent(_pytest.python.Class) if clscol: return clscol.obj
[ "def", "cls", "(", "self", ")", ":", "clscol", "=", "self", ".", "_pyfuncitem", ".", "getparent", "(", "_pytest", ".", "python", ".", "Class", ")", "if", "clscol", ":", "return", "clscol", ".", "obj" ]
[ 316, 4 ]
[ 320, 29 ]
python
en
['en', 'en', 'en']
True
FixtureRequest.instance
(self)
instance (can be None) on which test function was collected.
instance (can be None) on which test function was collected.
def instance(self): """ instance (can be None) on which test function was collected. """ # unittest support hack, see _pytest.unittest.TestCaseFunction try: return self._pyfuncitem._testcase except AttributeError: function = getattr(self, "function", None) ...
[ "def", "instance", "(", "self", ")", ":", "# unittest support hack, see _pytest.unittest.TestCaseFunction", "try", ":", "return", "self", ".", "_pyfuncitem", ".", "_testcase", "except", "AttributeError", ":", "function", "=", "getattr", "(", "self", ",", "\"function\"...
[ 323, 4 ]
[ 331, 54 ]
python
en
['en', 'en', 'en']
True
FixtureRequest.module
(self)
python module object where the test function was collected.
python module object where the test function was collected.
def module(self): """ python module object where the test function was collected. """ return self._pyfuncitem.getparent(_pytest.python.Module).obj
[ "def", "module", "(", "self", ")", ":", "return", "self", ".", "_pyfuncitem", ".", "getparent", "(", "_pytest", ".", "python", ".", "Module", ")", ".", "obj" ]
[ 334, 4 ]
[ 336, 68 ]
python
en
['en', 'en', 'en']
True
FixtureRequest.fspath
(self)
the file system path of the test module which collected this test.
the file system path of the test module which collected this test.
def fspath(self): """ the file system path of the test module which collected this test. """ return self._pyfuncitem.fspath
[ "def", "fspath", "(", "self", ")", ":", "return", "self", ".", "_pyfuncitem", ".", "fspath" ]
[ 339, 4 ]
[ 341, 38 ]
python
en
['en', 'en', 'en']
True
FixtureRequest.keywords
(self)
keywords/markers dictionary for the underlying node.
keywords/markers dictionary for the underlying node.
def keywords(self): """ keywords/markers dictionary for the underlying node. """ return self.node.keywords
[ "def", "keywords", "(", "self", ")", ":", "return", "self", ".", "node", ".", "keywords" ]
[ 344, 4 ]
[ 346, 33 ]
python
en
['en', 'en', 'en']
True
FixtureRequest.session
(self)
pytest session object.
pytest session object.
def session(self): """ pytest session object. """ return self._pyfuncitem.session
[ "def", "session", "(", "self", ")", ":", "return", "self", ".", "_pyfuncitem", ".", "session" ]
[ 349, 4 ]
[ 351, 39 ]
python
en
['en', 'en', 'en']
True
FixtureRequest.addfinalizer
(self, finalizer)
add finalizer/teardown function to be called after the last test within the requesting test context finished execution.
add finalizer/teardown function to be called after the last test within the requesting test context finished execution.
def addfinalizer(self, finalizer): """ add finalizer/teardown function to be called after the last test within the requesting test context finished execution. """ # XXX usually this method is shadowed by fixturedef specific ones self._addfinalizer(finalizer, scope=self.scope)
[ "def", "addfinalizer", "(", "self", ",", "finalizer", ")", ":", "# XXX usually this method is shadowed by fixturedef specific ones", "self", ".", "_addfinalizer", "(", "finalizer", ",", "scope", "=", "self", ".", "scope", ")" ]
[ 353, 4 ]
[ 358, 55 ]
python
en
['en', 'en', 'en']
True
FixtureRequest.applymarker
(self, marker)
Apply a marker to a single test function invocation. This method is useful if you don't want to have a keyword/marker on all function invocations. :arg marker: a :py:class:`_pytest.mark.MarkDecorator` object created by a call to ``pytest.mark.NAME(...)``.
Apply a marker to a single test function invocation. This method is useful if you don't want to have a keyword/marker on all function invocations.
def applymarker(self, marker): """ Apply a marker to a single test function invocation. This method is useful if you don't want to have a keyword/marker on all function invocations. :arg marker: a :py:class:`_pytest.mark.MarkDecorator` object created by a call to ``pytest.ma...
[ "def", "applymarker", "(", "self", ",", "marker", ")", ":", "try", ":", "self", ".", "node", ".", "keywords", "[", "marker", ".", "markname", "]", "=", "marker", "except", "AttributeError", ":", "raise", "ValueError", "(", "marker", ")" ]
[ 365, 4 ]
[ 376, 36 ]
python
en
['en', 'en', 'en']
True
FixtureRequest.raiseerror
(self, msg)
raise a FixtureLookupError with the given message.
raise a FixtureLookupError with the given message.
def raiseerror(self, msg): """ raise a FixtureLookupError with the given message. """ raise self._fixturemanager.FixtureLookupError(None, self, msg)
[ "def", "raiseerror", "(", "self", ",", "msg", ")", ":", "raise", "self", ".", "_fixturemanager", ".", "FixtureLookupError", "(", "None", ",", "self", ",", "msg", ")" ]
[ 378, 4 ]
[ 380, 70 ]
python
en
['en', 'en', 'en']
True
FixtureRequest.cached_setup
(self, setup, teardown=None, scope="module", extrakey=None)
(deprecated) Return a testing resource managed by ``setup`` & ``teardown`` calls. ``scope`` and ``extrakey`` determine when the ``teardown`` function will be called so that subsequent calls to ``setup`` would recreate the resource. With pytest-2.3 you often do not need ``cached_setup(...
(deprecated) Return a testing resource managed by ``setup`` & ``teardown`` calls. ``scope`` and ``extrakey`` determine when the ``teardown`` function will be called so that subsequent calls to ``setup`` would recreate the resource. With pytest-2.3 you often do not need ``cached_setup(...
def cached_setup(self, setup, teardown=None, scope="module", extrakey=None): """ (deprecated) Return a testing resource managed by ``setup`` & ``teardown`` calls. ``scope`` and ``extrakey`` determine when the ``teardown`` function will be called so that subsequent calls to ``setup`` wou...
[ "def", "cached_setup", "(", "self", ",", "setup", ",", "teardown", "=", "None", ",", "scope", "=", "\"module\"", ",", "extrakey", "=", "None", ")", ":", "if", "not", "hasattr", "(", "self", ".", "config", ",", "'_setupcache'", ")", ":", "self", ".", ...
[ 389, 4 ]
[ 419, 18 ]
python
en
['en', 'en', 'en']
True
FixtureRequest.getfixturevalue
(self, argname)
Dynamically run a named fixture function. Declaring fixtures via function argument is recommended where possible. But if you can only decide whether to use another fixture at test setup time, you may use this function to retrieve it inside a fixture or test function body.
Dynamically run a named fixture function.
def getfixturevalue(self, argname): """ Dynamically run a named fixture function. Declaring fixtures via function argument is recommended where possible. But if you can only decide whether to use another fixture at test setup time, you may use this function to retrieve it inside a fixtu...
[ "def", "getfixturevalue", "(", "self", ",", "argname", ")", ":", "return", "self", ".", "_get_active_fixturedef", "(", "argname", ")", ".", "cached_result", "[", "0", "]" ]
[ 421, 4 ]
[ 429, 68 ]
python
en
['en', 'en', 'en']
True
FixtureRequest.getfuncargvalue
(self, argname)
Deprecated, use getfixturevalue.
Deprecated, use getfixturevalue.
def getfuncargvalue(self, argname): """ Deprecated, use getfixturevalue. """ from _pytest import deprecated warnings.warn( deprecated.GETFUNCARGVALUE, DeprecationWarning, stacklevel=2) return self.getfixturevalue(argname)
[ "def", "getfuncargvalue", "(", "self", ",", "argname", ")", ":", "from", "_pytest", "import", "deprecated", "warnings", ".", "warn", "(", "deprecated", ".", "GETFUNCARGVALUE", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "return", "self", ".", ...
[ 431, 4 ]
[ 438, 44 ]
python
en
['en', 'ro', 'en']
True
FixtureRequest._compute_fixture_value
(self, fixturedef)
Creates a SubRequest based on "self" and calls the execute method of the given fixturedef object. This will force the FixtureDef object to throw away any previous results and compute a new fixture value, which will be stored into the FixtureDef object itself. :param FixtureDef fixtured...
Creates a SubRequest based on "self" and calls the execute method of the given fixturedef object. This will force the FixtureDef object to throw away any previous results and compute a new fixture value, which will be stored into the FixtureDef object itself.
def _compute_fixture_value(self, fixturedef): """ Creates a SubRequest based on "self" and calls the execute method of the given fixturedef object. This will force the FixtureDef object to throw away any previous results and compute a new fixture value, which will be stored into the Fixt...
[ "def", "_compute_fixture_value", "(", "self", ",", "fixturedef", ")", ":", "# prepare a subrequest object before calling fixture function", "# (latter managed by fixturedef)", "argname", "=", "fixturedef", ".", "argname", "funcitem", "=", "self", ".", "_pyfuncitem", "scope", ...
[ 469, 4 ]
[ 529, 66 ]
python
en
['en', 'error', 'th']
False
FixtureManager._getautousenames
(self, nodeid)
return a tuple of fixture names to be used.
return a tuple of fixture names to be used.
def _getautousenames(self, nodeid): """ return a tuple of fixture names to be used. """ autousenames = [] for baseid, basenames in self._nodeid_and_autousenames: if nodeid.startswith(baseid): if baseid: i = len(baseid) nextchar ...
[ "def", "_getautousenames", "(", "self", ",", "nodeid", ")", ":", "autousenames", "=", "[", "]", "for", "baseid", ",", "basenames", "in", "self", ".", "_nodeid_and_autousenames", ":", "if", "nodeid", ".", "startswith", "(", "baseid", ")", ":", "if", "baseid...
[ 1004, 4 ]
[ 1018, 27 ]
python
en
['en', 'en', 'en']
True
FixtureManager.getfixturedefs
(self, argname, nodeid)
Gets a list of fixtures which are applicable to the given node id. :param str argname: name of the fixture to search for :param str nodeid: full node id of the requesting test. :return: list[FixtureDef]
Gets a list of fixtures which are applicable to the given node id.
def getfixturedefs(self, argname, nodeid): """ Gets a list of fixtures which are applicable to the given node id. :param str argname: name of the fixture to search for :param str nodeid: full node id of the requesting test. :return: list[FixtureDef] """ try: ...
[ "def", "getfixturedefs", "(", "self", ",", "argname", ",", "nodeid", ")", ":", "try", ":", "fixturedefs", "=", "self", ".", "_arg2fixturedefs", "[", "argname", "]", "except", "KeyError", ":", "return", "None", "else", ":", "return", "tuple", "(", "self", ...
[ 1134, 4 ]
[ 1147, 67 ]
python
en
['en', 'error', 'th']
False
_contains_egg_info
(s)
Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1
Determine whether the string looks like an egg_info.
def _contains_egg_info(s): # type: (str) -> bool """Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 """ return bool(_egg_info_re.search(s))
[ "def", "_contains_egg_info", "(", "s", ")", ":", "# type: (str) -> bool", "return", "bool", "(", "_egg_info_re", ".", "search", "(", "s", ")", ")" ]
[ 36, 0 ]
[ 42, 39 ]
python
en
['en', 'en', 'en']
True
_should_build
( req, # type: InstallRequirement need_wheel, # type: bool check_binary_allowed, # type: BinaryAllowedPredicate )
Return whether an InstallRequirement should be built into a wheel.
Return whether an InstallRequirement should be built into a wheel.
def _should_build( req, # type: InstallRequirement need_wheel, # type: bool check_binary_allowed, # type: BinaryAllowedPredicate ): # type: (...) -> bool """Return whether an InstallRequirement should be built into a wheel.""" if req.constraint: # never build requirements that are mer...
[ "def", "_should_build", "(", "req", ",", "# type: InstallRequirement", "need_wheel", ",", "# type: bool", "check_binary_allowed", ",", "# type: BinaryAllowedPredicate", ")", ":", "# type: (...) -> bool", "if", "req", ".", "constraint", ":", "# never build requirements that ar...
[ 45, 0 ]
[ 87, 15 ]
python
en
['en', 'en', 'en']
True
_should_cache
( req, # type: InstallRequirement )
Return whether a built InstallRequirement can be stored in the persistent wheel cache, assuming the wheel cache is available, and _should_build() has determined a wheel needs to be built.
Return whether a built InstallRequirement can be stored in the persistent wheel cache, assuming the wheel cache is available, and _should_build() has determined a wheel needs to be built.
def _should_cache( req, # type: InstallRequirement ): # type: (...) -> Optional[bool] """ Return whether a built InstallRequirement can be stored in the persistent wheel cache, assuming the wheel cache is available, and _should_build() has determined a wheel needs to be built. """ if re...
[ "def", "_should_cache", "(", "req", ",", "# type: InstallRequirement", ")", ":", "# type: (...) -> Optional[bool]", "if", "req", ".", "editable", "or", "not", "req", ".", "source_dir", ":", "# never cache editable requirements", "return", "False", "if", "req", ".", ...
[ 109, 0 ]
[ 139, 16 ]
python
en
['en', 'error', 'th']
False
_get_cache_dir
( req, # type: InstallRequirement wheel_cache, # type: WheelCache )
Return the persistent or temporary cache directory where the built wheel need to be stored.
Return the persistent or temporary cache directory where the built wheel need to be stored.
def _get_cache_dir( req, # type: InstallRequirement wheel_cache, # type: WheelCache ): # type: (...) -> str """Return the persistent or temporary cache directory where the built wheel need to be stored. """ cache_available = bool(wheel_cache.cache_dir) assert req.link if cache_avai...
[ "def", "_get_cache_dir", "(", "req", ",", "# type: InstallRequirement", "wheel_cache", ",", "# type: WheelCache", ")", ":", "# type: (...) -> str", "cache_available", "=", "bool", "(", "wheel_cache", ".", "cache_dir", ")", "assert", "req", ".", "link", "if", "cache_...
[ 142, 0 ]
[ 156, 20 ]
python
en
['en', 'en', 'en']
True
_build_one
( req, # type: InstallRequirement output_dir, # type: str build_options, # type: List[str] global_options, # type: List[str] )
Build one wheel. :return: The filename of the built wheel, or None if the build failed.
Build one wheel.
def _build_one( req, # type: InstallRequirement output_dir, # type: str build_options, # type: List[str] global_options, # type: List[str] ): # type: (...) -> Optional[str] """Build one wheel. :return: The filename of the built wheel, or None if the build failed. """ try: ...
[ "def", "_build_one", "(", "req", ",", "# type: InstallRequirement", "output_dir", ",", "# type: str", "build_options", ",", "# type: List[str]", "global_options", ",", "# type: List[str]", ")", ":", "# type: (...) -> Optional[str]", "try", ":", "ensure_dir", "(", "output_...
[ 164, 0 ]
[ 188, 9 ]
python
en
['en', 'sr', 'en']
True
build
( requirements, # type: Iterable[InstallRequirement] wheel_cache, # type: WheelCache build_options, # type: List[str] global_options, # type: List[str] )
Build wheels. :return: The list of InstallRequirement that succeeded to build and the list of InstallRequirement that failed to build.
Build wheels.
def build( requirements, # type: Iterable[InstallRequirement] wheel_cache, # type: WheelCache build_options, # type: List[str] global_options, # type: List[str] ): # type: (...) -> BuildResult """Build wheels. :return: The list of InstallRequirement that succeeded to build and t...
[ "def", "build", "(", "requirements", ",", "# type: Iterable[InstallRequirement]", "wheel_cache", ",", "# type: WheelCache", "build_options", ",", "# type: List[str]", "global_options", ",", "# type: List[str]", ")", ":", "# type: (...) -> BuildResult", "if", "not", "requireme...
[ 258, 0 ]
[ 307, 42 ]
python
en
['en', 'sr', 'en']
False
intranges_from_list
(list_)
Represent a list of integers as a sequence of ranges: ((start_0, end_0), (start_1, end_1), ...), such that the original integers are exactly those x such that start_i <= x < end_i for some i. Ranges are encoded as single integers (start << 32 | end), not as tuples.
Represent a list of integers as a sequence of ranges: ((start_0, end_0), (start_1, end_1), ...), such that the original integers are exactly those x such that start_i <= x < end_i for some i.
def intranges_from_list(list_): """Represent a list of integers as a sequence of ranges: ((start_0, end_0), (start_1, end_1), ...), such that the original integers are exactly those x such that start_i <= x < end_i for some i. Ranges are encoded as single integers (start << 32 | end), not as tuples. ...
[ "def", "intranges_from_list", "(", "list_", ")", ":", "sorted_list", "=", "sorted", "(", "list_", ")", "ranges", "=", "[", "]", "last_write", "=", "-", "1", "for", "i", "in", "range", "(", "len", "(", "sorted_list", ")", ")", ":", "if", "i", "+", "...
[ 9, 0 ]
[ 28, 24 ]
python
en
['en', 'en', 'en']
True
intranges_contain
(int_, ranges)
Determine if `int_` falls into one of the ranges in `ranges`.
Determine if `int_` falls into one of the ranges in `ranges`.
def intranges_contain(int_, ranges): """Determine if `int_` falls into one of the ranges in `ranges`.""" tuple_ = _encode_range(int_, 0) pos = bisect.bisect_left(ranges, tuple_) # we could be immediately ahead of a tuple (start, end) # with start < int_ <= end if pos > 0: left, right = _...
[ "def", "intranges_contain", "(", "int_", ",", "ranges", ")", ":", "tuple_", "=", "_encode_range", "(", "int_", ",", "0", ")", "pos", "=", "bisect", ".", "bisect_left", "(", "ranges", ",", "tuple_", ")", "# we could be immediately ahead of a tuple (start, end)", ...
[ 37, 0 ]
[ 52, 16 ]
python
en
['en', 'en', 'en']
True
gitter_workspace_to_realm
( domain_name: str, gitter_data: GitterDataT, realm_subdomain: str )
Returns: 1. realm, converted realm data 2. avatars, which is list to map avatars to Zulip avatar records.json 3. user_map, which is a dictionary to map from Gitter user id to Zulip user id 4. stream_map, which is a dictionary to map from Gitter rooms to Zulip stream id
Returns: 1. realm, converted realm data 2. avatars, which is list to map avatars to Zulip avatar records.json 3. user_map, which is a dictionary to map from Gitter user id to Zulip user id 4. stream_map, which is a dictionary to map from Gitter rooms to Zulip stream id
def gitter_workspace_to_realm( domain_name: str, gitter_data: GitterDataT, realm_subdomain: str ) -> Tuple[ZerverFieldsT, List[ZerverFieldsT], Dict[str, int], Dict[str, int]]: """ Returns: 1. realm, converted realm data 2. avatars, which is list to map avatars to Zulip avatar records.json 3. use...
[ "def", "gitter_workspace_to_realm", "(", "domain_name", ":", "str", ",", "gitter_data", ":", "GitterDataT", ",", "realm_subdomain", ":", "str", ")", "->", "Tuple", "[", "ZerverFieldsT", ",", "List", "[", "ZerverFieldsT", "]", ",", "Dict", "[", "str", ",", "i...
[ 35, 0 ]
[ 61, 47 ]
python
en
['en', 'error', 'th']
False
build_userprofile
( timestamp: Any, domain_name: str, gitter_data: GitterDataT )
Returns: 1. zerver_userprofile, which is a list of user profile 2. avatar_list, which is list to map avatars to Zulip avatars records.json 3. added_users, which is a dictionary to map from Gitter user id to Zulip id
Returns: 1. zerver_userprofile, which is a list of user profile 2. avatar_list, which is list to map avatars to Zulip avatars records.json 3. added_users, which is a dictionary to map from Gitter user id to Zulip id
def build_userprofile( timestamp: Any, domain_name: str, gitter_data: GitterDataT ) -> Tuple[List[ZerverFieldsT], List[ZerverFieldsT], Dict[str, int]]: """ Returns: 1. zerver_userprofile, which is a list of user profile 2. avatar_list, which is list to map avatars to Zulip avatars records.json 3...
[ "def", "build_userprofile", "(", "timestamp", ":", "Any", ",", "domain_name", ":", "str", ",", "gitter_data", ":", "GitterDataT", ")", "->", "Tuple", "[", "List", "[", "ZerverFieldsT", "]", ",", "List", "[", "ZerverFieldsT", "]", ",", "Dict", "[", "str", ...
[ 64, 0 ]
[ 109, 52 ]
python
en
['en', 'error', 'th']
False
build_stream_map
( timestamp: Any, gitter_data: GitterDataT )
Returns: 1. stream, which is the list of streams 2. defaultstreams, which is the list of default streams 3. stream_map, which is a dictionary to map from Gitter rooms to Zulip stream id
Returns: 1. stream, which is the list of streams 2. defaultstreams, which is the list of default streams 3. stream_map, which is a dictionary to map from Gitter rooms to Zulip stream id
def build_stream_map( timestamp: Any, gitter_data: GitterDataT ) -> Tuple[List[ZerverFieldsT], List[ZerverFieldsT], Dict[str, int]]: """ Returns: 1. stream, which is the list of streams 2. defaultstreams, which is the list of default streams 3. stream_map, which is a dictionary to map from Gitte...
[ "def", "build_stream_map", "(", "timestamp", ":", "Any", ",", "gitter_data", ":", "GitterDataT", ")", "->", "Tuple", "[", "List", "[", "ZerverFieldsT", "]", ",", "List", "[", "ZerverFieldsT", "]", ",", "Dict", "[", "str", ",", "int", "]", "]", ":", "lo...
[ 118, 0 ]
[ 151, 46 ]
python
en
['en', 'error', 'th']
False
build_recipient_and_subscription
( zerver_userprofile: List[ZerverFieldsT], zerver_stream: List[ZerverFieldsT] )
Assumes that there is at least one stream with 'stream_id' = 0, and that this stream is the only defaultstream, with 'defaultstream_id' = 0 Returns: 1. zerver_recipient, which is a list of mapped recipient 2. zerver_subscription, which is a list of mapped subscription
Assumes that there is at least one stream with 'stream_id' = 0, and that this stream is the only defaultstream, with 'defaultstream_id' = 0 Returns: 1. zerver_recipient, which is a list of mapped recipient 2. zerver_subscription, which is a list of mapped subscription
def build_recipient_and_subscription( zerver_userprofile: List[ZerverFieldsT], zerver_stream: List[ZerverFieldsT] ) -> Tuple[List[ZerverFieldsT], List[ZerverFieldsT]]: """ Assumes that there is at least one stream with 'stream_id' = 0, and that this stream is the only defaultstream, with 'defaultstrea...
[ "def", "build_recipient_and_subscription", "(", "zerver_userprofile", ":", "List", "[", "ZerverFieldsT", "]", ",", "zerver_stream", ":", "List", "[", "ZerverFieldsT", "]", ")", "->", "Tuple", "[", "List", "[", "ZerverFieldsT", "]", ",", "List", "[", "ZerverField...
[ 154, 0 ]
[ 196, 48 ]
python
en
['en', 'error', 'th']
False
convert_gitter_workspace_messages
( gitter_data: GitterDataT, output_dir: str, subscriber_map: Dict[int, Set[int]], user_map: Dict[str, int], stream_map: Dict[str, int], user_short_name_to_full_name: Dict[str, str], chunk_size: int = MESSAGE_BATCH_CHUNK_SIZE, )
Messages are stored in batches
Messages are stored in batches
def convert_gitter_workspace_messages( gitter_data: GitterDataT, output_dir: str, subscriber_map: Dict[int, Set[int]], user_map: Dict[str, int], stream_map: Dict[str, int], user_short_name_to_full_name: Dict[str, str], chunk_size: int = MESSAGE_BATCH_CHUNK_SIZE, ) -> None: """ Messag...
[ "def", "convert_gitter_workspace_messages", "(", "gitter_data", ":", "GitterDataT", ",", "output_dir", ":", "str", ",", "subscriber_map", ":", "Dict", "[", "int", ",", "Set", "[", "int", "]", "]", ",", "user_map", ":", "Dict", "[", "str", ",", "int", "]", ...
[ 199, 0 ]
[ 266, 69 ]
python
en
['en', 'error', 'th']
False
develop._resolve_setup_path
(egg_base, install_dir, egg_path)
Generate a path from egg_base back to '.' where the setup script resides and ensure that path points to the setup path from $install_dir/$egg_path.
Generate a path from egg_base back to '.' where the setup script resides and ensure that path points to the setup path from $install_dir/$egg_path.
def _resolve_setup_path(egg_base, install_dir, egg_path): """ Generate a path from egg_base back to '.' where the setup script resides and ensure that path points to the setup path from $install_dir/$egg_path. """ path_to_setup = egg_base.replace(os.sep, '/').rstrip('/') ...
[ "def", "_resolve_setup_path", "(", "egg_base", ",", "install_dir", ",", "egg_path", ")", ":", "path_to_setup", "=", "egg_base", ".", "replace", "(", "os", ".", "sep", ",", "'/'", ")", ".", "rstrip", "(", "'/'", ")", "if", "path_to_setup", "!=", "os", "."...
[ 86, 4 ]
[ 103, 28 ]
python
en
['en', 'error', 'th']
False
pad_method_dict
(method_dict: Dict[str, bool])
Pads an authentication methods dict to contain all auth backends supported by the software, regardless of whether they are configured on this server
Pads an authentication methods dict to contain all auth backends supported by the software, regardless of whether they are configured on this server
def pad_method_dict(method_dict: Dict[str, bool]) -> Dict[str, bool]: """Pads an authentication methods dict to contain all auth backends supported by the software, regardless of whether they are configured on this server""" for key in AUTH_BACKEND_NAME_MAP: if key not in method_dict: ...
[ "def", "pad_method_dict", "(", "method_dict", ":", "Dict", "[", "str", ",", "bool", "]", ")", "->", "Dict", "[", "str", ",", "bool", "]", ":", "for", "key", "in", "AUTH_BACKEND_NAME_MAP", ":", "if", "key", "not", "in", "method_dict", ":", "method_dict", ...
[ 100, 0 ]
[ 107, 22 ]
python
en
['en', 'en', 'en']
True
any_social_backend_enabled
(realm: Optional[Realm] = None)
Used by the login page process to determine whether to show the 'OR' for login with Google
Used by the login page process to determine whether to show the 'OR' for login with Google
def any_social_backend_enabled(realm: Optional[Realm] = None) -> bool: """Used by the login page process to determine whether to show the 'OR' for login with Google""" social_backend_names = [ social_auth_subclass.auth_backend_name for social_auth_subclass in EXTERNAL_AUTH_METHODS ] return a...
[ "def", "any_social_backend_enabled", "(", "realm", ":", "Optional", "[", "Realm", "]", "=", "None", ")", "->", "bool", ":", "social_backend_names", "=", "[", "social_auth_subclass", ".", "auth_backend_name", "for", "social_auth_subclass", "in", "EXTERNAL_AUTH_METHODS"...
[ 161, 0 ]
[ 167, 59 ]
python
en
['en', 'en', 'en']
True
common_get_active_user
( email: str, realm: Realm, return_data: Optional[Dict[str, Any]] = None )
This is the core common function used by essentially all authentication backends to check if there's an active user account with a given email address in the organization, handling both user-level and realm-level deactivation correctly.
This is the core common function used by essentially all authentication backends to check if there's an active user account with a given email address in the organization, handling both user-level and realm-level deactivation correctly.
def common_get_active_user( email: str, realm: Realm, return_data: Optional[Dict[str, Any]] = None ) -> Optional[UserProfile]: """This is the core common function used by essentially all authentication backends to check if there's an active user account with a given email address in the organization, ha...
[ "def", "common_get_active_user", "(", "email", ":", "str", ",", "realm", ":", "Realm", ",", "return_data", ":", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", "=", "None", ")", "->", "Optional", "[", "UserProfile", "]", ":", "try", ":", "...
[ 194, 0 ]
[ 217, 23 ]
python
en
['en', 'en', 'en']
True
check_password_strength
(password: str)
Returns True if the password is strong enough, False otherwise.
Returns True if the password is strong enough, False otherwise.
def check_password_strength(password: str) -> bool: """ Returns True if the password is strong enough, False otherwise. """ if len(password) < settings.PASSWORD_MIN_LENGTH: return False if password == "": # zxcvbn throws an exception when passed the empty string, so # we...
[ "def", "check_password_strength", "(", "password", ":", "str", ")", "->", "bool", ":", "if", "len", "(", "password", ")", "<", "settings", ".", "PASSWORD_MIN_LENGTH", ":", "return", "False", "if", "password", "==", "\"\"", ":", "# zxcvbn throws an exception when...
[ 349, 0 ]
[ 365, 15 ]
python
en
['en', 'error', 'th']
False
find_ldap_users_by_email
(email: str)
Returns list of _LDAPUsers matching the email search, or None if no matches are found.
Returns list of _LDAPUsers matching the email search, or None if no matches are found.
def find_ldap_users_by_email(email: str) -> Optional[List[_LDAPUser]]: """ Returns list of _LDAPUsers matching the email search, or None if no matches are found. """ email_search = LDAPReverseEmailSearch(LDAPBackend(), email) return email_search.search_for_users(should_populate=False)
[ "def", "find_ldap_users_by_email", "(", "email", ":", "str", ")", "->", "Optional", "[", "List", "[", "_LDAPUser", "]", "]", ":", "email_search", "=", "LDAPReverseEmailSearch", "(", "LDAPBackend", "(", ")", ",", "email", ")", "return", "email_search", ".", "...
[ 442, 0 ]
[ 448, 63 ]
python
en
['en', 'error', 'th']
False
email_belongs_to_ldap
(realm: Realm, email: str)
Used to make determinations on whether a user's email address is managed by LDAP. For environments using both LDAP and Email+Password authentication, we do not allow EmailAuthBackend authentication for email addresses managed by LDAP (to avoid a security issue where one create separate credentials for ...
Used to make determinations on whether a user's email address is managed by LDAP. For environments using both LDAP and Email+Password authentication, we do not allow EmailAuthBackend authentication for email addresses managed by LDAP (to avoid a security issue where one create separate credentials for ...
def email_belongs_to_ldap(realm: Realm, email: str) -> bool: """Used to make determinations on whether a user's email address is managed by LDAP. For environments using both LDAP and Email+Password authentication, we do not allow EmailAuthBackend authentication for email addresses managed by LDAP (to a...
[ "def", "email_belongs_to_ldap", "(", "realm", ":", "Realm", ",", "email", ":", "str", ")", "->", "bool", ":", "if", "not", "ldap_auth_enabled", "(", "realm", ")", ":", "return", "False", "check_ldap_config", "(", ")", "if", "settings", ".", "LDAP_APPEND_DOMA...
[ 451, 0 ]
[ 471, 20 ]
python
en
['en', 'en', 'en']
True
catch_ldap_error
(signal: Signal, **kwargs: Any)
Inside django_auth_ldap populate_user(), if LDAPError is raised, e.g. due to invalid connection credentials, the function catches it and emits a signal (ldap_error) to communicate this error to others. We normally don't use signals, but here there's no choice, so in this function we essentially con...
Inside django_auth_ldap populate_user(), if LDAPError is raised, e.g. due to invalid connection credentials, the function catches it and emits a signal (ldap_error) to communicate this error to others. We normally don't use signals, but here there's no choice, so in this function we essentially con...
def catch_ldap_error(signal: Signal, **kwargs: Any) -> None: """ Inside django_auth_ldap populate_user(), if LDAPError is raised, e.g. due to invalid connection credentials, the function catches it and emits a signal (ldap_error) to communicate this error to others. We normally don't use signals, bu...
[ "def", "catch_ldap_error", "(", "signal", ":", "Signal", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "kwargs", "[", "\"context\"", "]", "==", "\"populate_user\"", ":", "# The exception message can contain the password (if it was invalid),", "#...
[ 982, 0 ]
[ 994, 75 ]
python
en
['en', 'error', 'th']
False
social_associate_user_helper
( backend: BaseAuth, return_data: Dict[str, Any], *args: Any, **kwargs: Any )
Responsible for doing the Zulip account lookup and validation parts of the Zulip social auth pipeline (similar to the authenticate() methods in most other auth backends in this file). Returns a UserProfile object for successful authentication, and None otherwise.
Responsible for doing the Zulip account lookup and validation parts of the Zulip social auth pipeline (similar to the authenticate() methods in most other auth backends in this file).
def social_associate_user_helper( backend: BaseAuth, return_data: Dict[str, Any], *args: Any, **kwargs: Any ) -> Union[HttpResponse, Optional[UserProfile]]: """Responsible for doing the Zulip account lookup and validation parts of the Zulip social auth pipeline (similar to the authenticate() methods in ...
[ "def", "social_associate_user_helper", "(", "backend", ":", "BaseAuth", ",", "return_data", ":", "Dict", "[", "str", ",", "Any", "]", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Union", "[", "HttpResponse", ",", "Opti...
[ 1289, 0 ]
[ 1427, 23 ]
python
en
['en', 'en', 'en']
True
social_auth_associate_user
( backend: BaseAuth, *args: Any, **kwargs: Any )
A simple wrapper function to reformat the return data from social_associate_user_helper as a dictionary. The python-social-auth infrastructure will then pass those values into later stages of settings.SOCIAL_AUTH_PIPELINE, such as social_auth_finish, as kwargs.
A simple wrapper function to reformat the return data from social_associate_user_helper as a dictionary. The python-social-auth infrastructure will then pass those values into later stages of settings.SOCIAL_AUTH_PIPELINE, such as social_auth_finish, as kwargs.
def social_auth_associate_user( backend: BaseAuth, *args: Any, **kwargs: Any ) -> Union[HttpResponse, Dict[str, Any]]: """A simple wrapper function to reformat the return data from social_associate_user_helper as a dictionary. The python-social-auth infrastructure will then pass those values into l...
[ "def", "social_auth_associate_user", "(", "backend", ":", "BaseAuth", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Union", "[", "HttpResponse", ",", "Dict", "[", "str", ",", "Any", "]", "]", ":", "partial_token", "=", ...
[ 1431, 0 ]
[ 1452, 9 ]
python
en
['en', 'en', 'en']
True
social_auth_finish
( backend: Any, details: Dict[str, Any], response: HttpResponse, *args: Any, **kwargs: Any )
Given the determination in social_auth_associate_user for whether the user should be authenticated, this takes care of actually logging in the user (if appropriate) and redirecting the browser to the appropriate next page depending on the situation. Read the comments below as well as login_or_register_...
Given the determination in social_auth_associate_user for whether the user should be authenticated, this takes care of actually logging in the user (if appropriate) and redirecting the browser to the appropriate next page depending on the situation. Read the comments below as well as login_or_register_...
def social_auth_finish( backend: Any, details: Dict[str, Any], response: HttpResponse, *args: Any, **kwargs: Any ) -> Optional[HttpResponse]: """Given the determination in social_auth_associate_user for whether the user should be authenticated, this takes care of actually logging in the user (if appropr...
[ "def", "social_auth_finish", "(", "backend", ":", "Any", ",", "details", ":", "Dict", "[", "str", ",", "Any", "]", ",", "response", ":", "HttpResponse", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Optional", "[", ...
[ 1455, 0 ]
[ 1582, 50 ]
python
en
['en', 'en', 'en']
True
get_external_method_dicts
(realm: Optional[Realm] = None)
Returns a list of dictionaries that represent social backends, sorted in the order in which they should be displayed.
Returns a list of dictionaries that represent social backends, sorted in the order in which they should be displayed.
def get_external_method_dicts(realm: Optional[Realm] = None) -> List[ExternalAuthMethodDictT]: """ Returns a list of dictionaries that represent social backends, sorted in the order in which they should be displayed. """ result: List[ExternalAuthMethodDictT] = [] for backend in EXTERNAL_AUTH_MET...
[ "def", "get_external_method_dicts", "(", "realm", ":", "Optional", "[", "Realm", "]", "=", "None", ")", "->", "List", "[", "ExternalAuthMethodDictT", "]", ":", "result", ":", "List", "[", "ExternalAuthMethodDictT", "]", "=", "[", "]", "for", "backend", "in",...
[ 2276, 0 ]
[ 2288, 17 ]
python
en
['en', 'error', 'th']
False
ZulipAuthMixin.get_user
(self, user_profile_id: int)
Override the Django method for getting a UserProfile object from the user_profile_id,.
Override the Django method for getting a UserProfile object from the user_profile_id,.
def get_user(self, user_profile_id: int) -> Optional[UserProfile]: """Override the Django method for getting a UserProfile object from the user_profile_id,.""" try: return get_user_profile_by_id(user_profile_id) except UserProfile.DoesNotExist: return None
[ "def", "get_user", "(", "self", ",", "user_profile_id", ":", "int", ")", "->", "Optional", "[", "UserProfile", "]", ":", "try", ":", "return", "get_user_profile_by_id", "(", "user_profile_id", ")", "except", "UserProfile", ".", "DoesNotExist", ":", "return", "...
[ 317, 4 ]
[ 323, 23 ]
python
en
['en', 'en', 'en']
True
EmailAuthBackend.authenticate
( self, request: HttpRequest, *, username: str, password: str, realm: Realm, return_data: Optional[Dict[str, Any]] = None, )
Authenticate a user based on email address as the user name.
Authenticate a user based on email address as the user name.
def authenticate( self, request: HttpRequest, *, username: str, password: str, realm: Realm, return_data: Optional[Dict[str, Any]] = None, ) -> Optional[UserProfile]: """Authenticate a user based on email address as the user name.""" if not pas...
[ "def", "authenticate", "(", "self", ",", "request", ":", "HttpRequest", ",", "*", ",", "username", ":", "str", ",", "password", ":", "str", ",", "realm", ":", "Realm", ",", "return_data", ":", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]"...
[ 378, 4 ]
[ 425, 19 ]
python
en
['en', 'en', 'en']
True
ZulipLDAPAuthBackendBase.django_to_ldap_username
(self, username: str)
Translates django username (user_profile.delivery_email or whatever the user typed in the login field when authenticating via the LDAP backend) into LDAP username. Guarantees that the username it returns actually has an entry in the LDAP directory. Raises ZulipLDAPExceptionNoMatchingLDA...
Translates django username (user_profile.delivery_email or whatever the user typed in the login field when authenticating via the LDAP backend) into LDAP username. Guarantees that the username it returns actually has an entry in the LDAP directory. Raises ZulipLDAPExceptionNoMatchingLDA...
def django_to_ldap_username(self, username: str) -> str: """ Translates django username (user_profile.delivery_email or whatever the user typed in the login field when authenticating via the LDAP backend) into LDAP username. Guarantees that the username it returns actually has an entry i...
[ "def", "django_to_ldap_username", "(", "self", ",", "username", ":", "str", ")", "->", "str", ":", "result", "=", "username", "if", "settings", ".", "LDAP_APPEND_DOMAIN", ":", "if", "is_valid_email", "(", "username", ")", ":", "if", "not", "username", ".", ...
[ 533, 4 ]
[ 573, 21 ]
python
en
['en', 'error', 'th']
False
ZulipLDAPAuthBackendBase.ldap_to_django_username
(self, username: str)
This is called inside django_auth_ldap with only one role: to convert _LDAPUser._username to django username (so in Zulip, the email) and pass that as "username" argument to get_or_build_user(username, ldapuser). In many cases, the email is stored in the _LDAPUser's attributes, so it ca...
This is called inside django_auth_ldap with only one role: to convert _LDAPUser._username to django username (so in Zulip, the email) and pass that as "username" argument to get_or_build_user(username, ldapuser). In many cases, the email is stored in the _LDAPUser's attributes, so it ca...
def ldap_to_django_username(self, username: str) -> str: """ This is called inside django_auth_ldap with only one role: to convert _LDAPUser._username to django username (so in Zulip, the email) and pass that as "username" argument to get_or_build_user(username, ldapuser). In man...
[ "def", "ldap_to_django_username", "(", "self", ",", "username", ":", "str", ")", "->", "str", ":", "return", "username" ]
[ 595, 4 ]
[ 605, 23 ]
python
en
['en', 'error', 'th']
False
ZulipLDAPAuthBackendBase.is_account_control_disabled_user
(self, ldap_user: _LDAPUser)
Implements the userAccountControl check for whether a user has been disabled in an Active Directory server being integrated with Zulip via LDAP.
Implements the userAccountControl check for whether a user has been disabled in an Active Directory server being integrated with Zulip via LDAP.
def is_account_control_disabled_user(self, ldap_user: _LDAPUser) -> bool: """Implements the userAccountControl check for whether a user has been disabled in an Active Directory server being integrated with Zulip via LDAP.""" account_control_value = ldap_user.attrs[ settings.A...
[ "def", "is_account_control_disabled_user", "(", "self", ",", "ldap_user", ":", "_LDAPUser", ")", "->", "bool", ":", "account_control_value", "=", "ldap_user", ".", "attrs", "[", "settings", ".", "AUTH_LDAP_USER_ATTR_MAP", "[", "\"userAccountControl\"", "]", "]", "["...
[ 641, 4 ]
[ 649, 28 ]
python
en
['en', 'en', 'en']
True
ZulipLDAPAuthBackendBase.get_mapped_name
(cls, ldap_user: _LDAPUser)
Constructs the user's Zulip full_name from the LDAP data
Constructs the user's Zulip full_name from the LDAP data
def get_mapped_name(cls, ldap_user: _LDAPUser) -> str: """Constructs the user's Zulip full_name from the LDAP data""" if "full_name" in settings.AUTH_LDAP_USER_ATTR_MAP: full_name_attr = settings.AUTH_LDAP_USER_ATTR_MAP["full_name"] full_name = ldap_user.attrs[full_name_attr][0] ...
[ "def", "get_mapped_name", "(", "cls", ",", "ldap_user", ":", "_LDAPUser", ")", "->", "str", ":", "if", "\"full_name\"", "in", "settings", ".", "AUTH_LDAP_USER_ATTR_MAP", ":", "full_name_attr", "=", "settings", ".", "AUTH_LDAP_USER_ATTR_MAP", "[", "\"full_name\"", ...
[ 694, 4 ]
[ 708, 24 ]
python
en
['en', 'en', 'en']
True
ZulipLDAPAuthBackend.get_or_build_user
(self, username: str, ldap_user: _LDAPUser)
The main function of our authentication backend extension of django-auth-ldap. When this is called (from `authenticate`), django-auth-ldap will already have verified that the provided username and password match those in the LDAP database. This function's responsibility is to check (1)...
The main function of our authentication backend extension of django-auth-ldap. When this is called (from `authenticate`), django-auth-ldap will already have verified that the provided username and password match those in the LDAP database.
def get_or_build_user(self, username: str, ldap_user: _LDAPUser) -> Tuple[UserProfile, bool]: """The main function of our authentication backend extension of django-auth-ldap. When this is called (from `authenticate`), django-auth-ldap will already have verified that the provided userna...
[ "def", "get_or_build_user", "(", "self", ",", "username", ":", "str", ",", "ldap_user", ":", "_LDAPUser", ")", "->", "Tuple", "[", "UserProfile", ",", "bool", "]", ":", "return_data", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "}", "username",...
[ 810, 4 ]
[ 900, 33 ]
python
en
['en', 'en', 'en']
True
ZulipLDAPUserPopulator.get_or_build_user
( self, username: str, ldap_user: ZulipLDAPUser )
This is used only in non-authentication contexts such as: ./manage.py sync_ldap_user_data
This is used only in non-authentication contexts such as: ./manage.py sync_ldap_user_data
def get_or_build_user( self, username: str, ldap_user: ZulipLDAPUser ) -> Tuple[UserProfile, bool]: """This is used only in non-authentication contexts such as: ./manage.py sync_ldap_user_data """ # Obtain the django username from the ldap_user object: username = self...
[ "def", "get_or_build_user", "(", "self", ",", "username", ":", "str", ",", "ldap_user", ":", "ZulipLDAPUser", ")", "->", "Tuple", "[", "UserProfile", ",", "bool", "]", ":", "# Obtain the django username from the ldap_user object:", "username", "=", "self", ".", "u...
[ 938, 4 ]
[ 974, 28 ]
python
en
['en', 'en', 'en']
True
ExternalAuthMethod.dict_representation
(cls, realm: Optional[Realm] = None)
Method returning dictionaries representing the authentication methods corresponding to the backend that subclasses this. The documentation for the external_authentication_methods field of the /server_settings endpoint explains the details of these dictionaries. This returns a li...
Method returning dictionaries representing the authentication methods corresponding to the backend that subclasses this. The documentation for the external_authentication_methods field of the /server_settings endpoint explains the details of these dictionaries. This returns a li...
def dict_representation(cls, realm: Optional[Realm] = None) -> List[ExternalAuthMethodDictT]: """ Method returning dictionaries representing the authentication methods corresponding to the backend that subclasses this. The documentation for the external_authentication_methods field of th...
[ "def", "dict_representation", "(", "cls", ",", "realm", ":", "Optional", "[", "Realm", "]", "=", "None", ")", "->", "List", "[", "ExternalAuthMethodDictT", "]", ":" ]
[ 1110, 4 ]
[ 1118, 11 ]
python
en
['en', 'error', 'th']
False
SocialAuthMixin.auth_complete
(self, *args: Any, **kwargs: Any)
This is a small wrapper around the core `auth_complete` method of python-social-auth, designed primarily to prevent 500s for exceptions in the social auth code from situations that are really user errors. Returning `None` from this function will redirect the browser to the login page. ...
This is a small wrapper around the core `auth_complete` method of python-social-auth, designed primarily to prevent 500s for exceptions in the social auth code from situations that are really user errors. Returning `None` from this function will redirect the browser to the login page. ...
def auth_complete(self, *args: Any, **kwargs: Any) -> Optional[HttpResponse]: """This is a small wrapper around the core `auth_complete` method of python-social-auth, designed primarily to prevent 500s for exceptions in the social auth code from situations that are really user errors. R...
[ "def", "auth_complete", "(", "self", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Optional", "[", "HttpResponse", "]", ":", "try", ":", "# Call the auth_complete method of social_core.backends.oauth.BaseOAuth2", "return", "super",...
[ 1600, 4 ]
[ 1622, 23 ]
python
en
['en', 'en', 'en']
True
_get_mro
(cls)
Returns the bases classes for cls sorted by the MRO. Works around an issue on Jython where inspect.getmro will not return all base classes if multiple classes share the same name. Instead, this function will return a tuple containing the class itself, and the contents of cls.__bases__. See https:/...
Returns the bases classes for cls sorted by the MRO.
def _get_mro(cls): """ Returns the bases classes for cls sorted by the MRO. Works around an issue on Jython where inspect.getmro will not return all base classes if multiple classes share the same name. Instead, this function will return a tuple containing the class itself, and the contents of ...
[ "def", "_get_mro", "(", "cls", ")", ":", "if", "platform", ".", "python_implementation", "(", ")", "==", "\"Jython\"", ":", "return", "(", "cls", ",", ")", "+", "cls", ".", "__bases__", "return", "inspect", ".", "getmro", "(", "cls", ")" ]
[ 21, 0 ]
[ 32, 30 ]
python
en
['en', 'error', 'th']
False
get_unpatched_class
(cls)
Protect against re-patching the distutils if reloaded Also ensures that no other distutils extension monkeypatched the distutils first.
Protect against re-patching the distutils if reloaded
def get_unpatched_class(cls): """Protect against re-patching the distutils if reloaded Also ensures that no other distutils extension monkeypatched the distutils first. """ external_bases = ( cls for cls in _get_mro(cls) if not cls.__module__.startswith('setuptools') ) ...
[ "def", "get_unpatched_class", "(", "cls", ")", ":", "external_bases", "=", "(", "cls", "for", "cls", "in", "_get_mro", "(", "cls", ")", "if", "not", "cls", ".", "__module__", ".", "startswith", "(", "'setuptools'", ")", ")", "base", "=", "next", "(", "...
[ 44, 0 ]
[ 59, 15 ]
python
en
['en', 'en', 'en']
True
_patch_distribution_metadata
()
Patch write_pkg_file and read_pkg_file for higher metadata standards
Patch write_pkg_file and read_pkg_file for higher metadata standards
def _patch_distribution_metadata(): """Patch write_pkg_file and read_pkg_file for higher metadata standards""" for attr in ('write_pkg_file', 'read_pkg_file', 'get_metadata_version'): new_val = getattr(setuptools.dist, attr) setattr(distutils.dist.DistributionMetadata, attr, new_val)
[ "def", "_patch_distribution_metadata", "(", ")", ":", "for", "attr", "in", "(", "'write_pkg_file'", ",", "'read_pkg_file'", ",", "'get_metadata_version'", ")", ":", "new_val", "=", "getattr", "(", "setuptools", ".", "dist", ",", "attr", ")", "setattr", "(", "d...
[ 101, 0 ]
[ 105, 67 ]
python
en
['en', 'en', 'en']
True
patch_func
(replacement, target_mod, func_name)
Patch func_name in target_mod with replacement Important - original must be resolved by name to avoid patching an already patched function.
Patch func_name in target_mod with replacement
def patch_func(replacement, target_mod, func_name): """ Patch func_name in target_mod with replacement Important - original must be resolved by name to avoid patching an already patched function. """ original = getattr(target_mod, func_name) # set the 'unpatched' attribute on the replaceme...
[ "def", "patch_func", "(", "replacement", ",", "target_mod", ",", "func_name", ")", ":", "original", "=", "getattr", "(", "target_mod", ",", "func_name", ")", "# set the 'unpatched' attribute on the replacement to", "# point to the original.", "vars", "(", "replacement", ...
[ 108, 0 ]
[ 122, 47 ]
python
en
['en', 'error', 'th']
False
patch_for_msvc_specialized_compiler
()
Patch functions in distutils to use standalone Microsoft Visual C++ compilers.
Patch functions in distutils to use standalone Microsoft Visual C++ compilers.
def patch_for_msvc_specialized_compiler(): """ Patch functions in distutils to use standalone Microsoft Visual C++ compilers. """ # import late to avoid circular imports on Python < 3.5 msvc = import_module('setuptools.msvc') if platform.system() != 'Windows': # Compilers only avail...
[ "def", "patch_for_msvc_specialized_compiler", "(", ")", ":", "# import late to avoid circular imports on Python < 3.5", "msvc", "=", "import_module", "(", "'setuptools.msvc'", ")", "if", "platform", ".", "system", "(", ")", "!=", "'Windows'", ":", "# Compilers only availabl...
[ 129, 0 ]
[ 176, 12 ]
python
en
['en', 'error', 'th']
False
filter_traceback
(entry)
Return True if a TracebackEntry instance should be removed from tracebacks: * dynamically generated code (no code to show up for it); * internal traceback from pytest or its internal libraries, py and pluggy.
Return True if a TracebackEntry instance should be removed from tracebacks: * dynamically generated code (no code to show up for it); * internal traceback from pytest or its internal libraries, py and pluggy.
def filter_traceback(entry): """Return True if a TracebackEntry instance should be removed from tracebacks: * dynamically generated code (no code to show up for it); * internal traceback from pytest or its internal libraries, py and pluggy. """ # entry.path might sometimes return a str object when t...
[ "def", "filter_traceback", "(", "entry", ")", ":", "# entry.path might sometimes return a str object when the entry", "# points to dynamically generated code", "# see https://bitbucket.org/pytest-dev/py/issues/71", "raw_filename", "=", "entry", ".", "frame", ".", "code", ".", "raw"...
[ 45, 0 ]
[ 60, 89 ]
python
en
['en', 'en', 'en']
True
_get_xunit_setup_teardown
(holder, attr_name, param_obj=None)
Return a callable to perform xunit-style setup or teardown if the function exists in the ``holder`` object. The ``param_obj`` parameter is the parameter which will be passed to the function when the callable is called without arguments, defaults to the ``holder`` object. Return ``None`` if a suitab...
Return a callable to perform xunit-style setup or teardown if the function exists in the ``holder`` object. The ``param_obj`` parameter is the parameter which will be passed to the function when the callable is called without arguments, defaults to the ``holder`` object. Return ``None`` if a suitab...
def _get_xunit_setup_teardown(holder, attr_name, param_obj=None): """ Return a callable to perform xunit-style setup or teardown if the function exists in the ``holder`` object. The ``param_obj`` parameter is the parameter which will be passed to the function when the callable is called without argu...
[ "def", "_get_xunit_setup_teardown", "(", "holder", ",", "attr_name", ",", "param_obj", "=", "None", ")", ":", "param_obj", "=", "param_obj", "if", "param_obj", "is", "not", "None", "else", "holder", "result", "=", "_get_xunit_func", "(", "holder", ",", "attr_n...
[ 465, 0 ]
[ 482, 25 ]
python
en
['en', 'error', 'th']
False
_get_xunit_func
(obj, name)
Return the attribute from the given object to be used as a setup/teardown xunit-style function, but only if not marked as a fixture to avoid calling it twice.
Return the attribute from the given object to be used as a setup/teardown xunit-style function, but only if not marked as a fixture to avoid calling it twice.
def _get_xunit_func(obj, name): """Return the attribute from the given object to be used as a setup/teardown xunit-style function, but only if not marked as a fixture to avoid calling it twice. """ meth = getattr(obj, name, None) if fixtures.getfixturemarker(meth) is None: return meth
[ "def", "_get_xunit_func", "(", "obj", ",", "name", ")", ":", "meth", "=", "getattr", "(", "obj", ",", "name", ",", "None", ")", "if", "fixtures", ".", "getfixturemarker", "(", "meth", ")", "is", "None", ":", "return", "meth" ]
[ 485, 0 ]
[ 492, 19 ]
python
en
['en', 'en', 'en']
True
_find_parametrized_scope
(argnames, arg2fixturedefs, indirect)
Find the most appropriate scope for a parametrized call based on its arguments. When there's at least one direct argument, always use "function" scope. When a test function is parametrized and all its arguments are indirect (e.g. fixtures), return the most narrow scope based on the fixtures used. Rel...
Find the most appropriate scope for a parametrized call based on its arguments.
def _find_parametrized_scope(argnames, arg2fixturedefs, indirect): """Find the most appropriate scope for a parametrized call based on its arguments. When there's at least one direct argument, always use "function" scope. When a test function is parametrized and all its arguments are indirect (e.g. fi...
[ "def", "_find_parametrized_scope", "(", "argnames", ",", "arg2fixturedefs", ",", "indirect", ")", ":", "from", "_pytest", ".", "fixtures", "import", "scopes", "indirect_as_list", "=", "isinstance", "(", "indirect", ",", "(", "list", ",", "tuple", ")", ")", "al...
[ 889, 0 ]
[ 912, 21 ]
python
en
['en', 'en', 'en']
True
PyobjMixin.getmodpath
(self, stopatmodule=True, includemodule=False)
return python path relative to the containing module.
return python path relative to the containing module.
def getmodpath(self, stopatmodule=True, includemodule=False): """ return python path relative to the containing module. """ chain = self.listchain() chain.reverse() parts = [] for node in chain: if isinstance(node, Instance): continue name ...
[ "def", "getmodpath", "(", "self", ",", "stopatmodule", "=", "True", ",", "includemodule", "=", "False", ")", ":", "chain", "=", "self", ".", "listchain", "(", ")", "chain", ".", "reverse", "(", ")", "parts", "=", "[", "]", "for", "node", "in", "chain...
[ 231, 4 ]
[ 249, 35 ]
python
en
['en', 'en', 'en']
True