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
read_classification_results
(storage_client, file_path)
Reads classification results from the file in Cloud Storage. This method reads file with classification results produced by running defense on singe batch of adversarial images. Args: storage_client: instance of CompetitionStorageClient or None for local file file_path: path of the file with r...
Reads classification results from the file in Cloud Storage.
def read_classification_results(storage_client, file_path): """Reads classification results from the file in Cloud Storage. This method reads file with classification results produced by running defense on singe batch of adversarial images. Args: storage_client: instance of CompetitionStorageCli...
[ "def", "read_classification_results", "(", "storage_client", ",", "file_path", ")", ":", "if", "storage_client", ":", "# file on Cloud", "success", "=", "False", "retry_count", "=", "0", "while", "retry_count", "<", "4", ":", "try", ":", "blob", "=", "storage_cl...
[ 29, 0 ]
[ 90, 17 ]
python
en
['en', 'en', 'en']
True
analyze_one_classification_result
( storage_client, file_path, adv_batch, dataset_batches, dataset_meta )
Reads and analyzes one classification result. This method reads file with classification result and counts how many images were classified correctly and incorrectly, how many times target class was hit and total number of images. Args: storage_client: instance of CompetitionStorageClient f...
Reads and analyzes one classification result.
def analyze_one_classification_result( storage_client, file_path, adv_batch, dataset_batches, dataset_meta ): """Reads and analyzes one classification result. This method reads file with classification result and counts how many images were classified correctly and incorrectly, how many times targe...
[ "def", "analyze_one_classification_result", "(", "storage_client", ",", "file_path", ",", "adv_batch", ",", "dataset_batches", ",", "dataset_meta", ")", ":", "class_result", "=", "read_classification_results", "(", "storage_client", ",", "file_path", ")", "if", "class_r...
[ 93, 0 ]
[ 140, 5 ]
python
en
['en', 'en', 'en']
True
ResultMatrix.__init__
(self, default_value=0)
Initializes empty matrix.
Initializes empty matrix.
def __init__(self, default_value=0): """Initializes empty matrix.""" self._items = {} self._dim0 = set() self._dim1 = set() self._default_value = default_value
[ "def", "__init__", "(", "self", ",", "default_value", "=", "0", ")", ":", "self", ".", "_items", "=", "{", "}", "self", ".", "_dim0", "=", "set", "(", ")", "self", ".", "_dim1", "=", "set", "(", ")", "self", ".", "_default_value", "=", "default_val...
[ 149, 4 ]
[ 154, 43 ]
python
en
['pt', 'pl', 'en']
False
ResultMatrix.dim0
(self)
Returns set of rows.
Returns set of rows.
def dim0(self): """Returns set of rows.""" return self._dim0
[ "def", "dim0", "(", "self", ")", ":", "return", "self", ".", "_dim0" ]
[ 157, 4 ]
[ 159, 25 ]
python
en
['en', 'en', 'en']
True
ResultMatrix.dim1
(self)
Returns set of columns.
Returns set of columns.
def dim1(self): """Returns set of columns.""" return self._dim1
[ "def", "dim1", "(", "self", ")", ":", "return", "self", ".", "_dim1" ]
[ 162, 4 ]
[ 164, 25 ]
python
en
['en', 'ru', 'en']
True
ResultMatrix.__getitem__
(self, key)
Returns element of the matrix indexed by given key. Args: key: tuple of (row_idx, column_idx) Returns: Element of the matrix Raises: IndexError: if key is invalid.
Returns element of the matrix indexed by given key.
def __getitem__(self, key): """Returns element of the matrix indexed by given key. Args: key: tuple of (row_idx, column_idx) Returns: Element of the matrix Raises: IndexError: if key is invalid. """ if not isinstance(key, tuple) or len(key...
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "if", "not", "isinstance", "(", "key", ",", "tuple", ")", "or", "len", "(", "key", ")", "!=", "2", ":", "raise", "IndexError", "(", "\"Invalid index: {0}\"", ".", "format", "(", "key", ")", ")"...
[ 166, 4 ]
[ 180, 56 ]
python
en
['en', 'en', 'en']
True
ResultMatrix.__setitem__
(self, key, value)
Sets element of the matrix at position indexed by key. Args: key: tuple of (row_idx, column_idx) value: new value of the element of the matrix Raises: IndexError: if key is invalid.
Sets element of the matrix at position indexed by key.
def __setitem__(self, key, value): """Sets element of the matrix at position indexed by key. Args: key: tuple of (row_idx, column_idx) value: new value of the element of the matrix Raises: IndexError: if key is invalid. """ if not isinstance(key, t...
[ "def", "__setitem__", "(", "self", ",", "key", ",", "value", ")", ":", "if", "not", "isinstance", "(", "key", ",", "tuple", ")", "or", "len", "(", "key", ")", "!=", "2", ":", "raise", "IndexError", "(", "\"Invalid index: {0}\"", ".", "format", "(", "...
[ 182, 4 ]
[ 196, 32 ]
python
en
['en', 'en', 'en']
True
ResultMatrix.save_to_file
(self, filename, remap_dim0=None, remap_dim1=None)
Saves matrix to the file. Args: filename: name of the file where to save matrix remap_dim0: dictionary with mapping row indices to row names which should be saved to file. If none then indices will be used as names. remap_dim1: dictionary with mapping column indices to...
Saves matrix to the file.
def save_to_file(self, filename, remap_dim0=None, remap_dim1=None): """Saves matrix to the file. Args: filename: name of the file where to save matrix remap_dim0: dictionary with mapping row indices to row names which should be saved to file. If none then indices will be...
[ "def", "save_to_file", "(", "self", ",", "filename", ",", "remap_dim0", "=", "None", ",", "remap_dim1", "=", "None", ")", ":", "# rows - first index", "# columns - second index", "with", "open", "(", "filename", ",", "\"w\"", ")", "as", "fobj", ":", "columns",...
[ 198, 4 ]
[ 221, 32 ]
python
en
['en', 'en', 'en']
True
ClassificationBatches.__init__
(self, datastore_client, storage_client, round_name)
Initializes ClassificationBatches. Args: datastore_client: instance of CompetitionDatastoreClient storage_client: instance of CompetitionStorageClient round_name: name of the round
Initializes ClassificationBatches.
def __init__(self, datastore_client, storage_client, round_name): """Initializes ClassificationBatches. Args: datastore_client: instance of CompetitionDatastoreClient storage_client: instance of CompetitionStorageClient round_name: name of the round """ sel...
[ "def", "__init__", "(", "self", ",", "datastore_client", ",", "storage_client", ",", "round_name", ")", ":", "self", ".", "_datastore_client", "=", "datastore_client", "self", ".", "_storage_client", "=", "storage_client", "self", ".", "_round_name", "=", "round_n...
[ 231, 4 ]
[ 243, 23 ]
python
it
['pl', 'la', 'it']
False
ClassificationBatches.serialize
(self, fobj)
Serializes data stored in this class.
Serializes data stored in this class.
def serialize(self, fobj): """Serializes data stored in this class.""" pickle.dump(self._data, fobj)
[ "def", "serialize", "(", "self", ",", "fobj", ")", ":", "pickle", ".", "dump", "(", "self", ".", "_data", ",", "fobj", ")" ]
[ 245, 4 ]
[ 247, 37 ]
python
en
['en', 'en', 'en']
True
ClassificationBatches.deserialize
(self, fobj)
Deserializes data from file into this class.
Deserializes data from file into this class.
def deserialize(self, fobj): """Deserializes data from file into this class.""" self._data = pickle.load(fobj)
[ "def", "deserialize", "(", "self", ",", "fobj", ")", ":", "self", ".", "_data", "=", "pickle", ".", "load", "(", "fobj", ")" ]
[ 249, 4 ]
[ 251, 38 ]
python
en
['en', 'en', 'en']
True
ClassificationBatches.data
(self)
Returns dictionary with data.
Returns dictionary with data.
def data(self): """Returns dictionary with data.""" return self._data
[ "def", "data", "(", "self", ")", ":", "return", "self", ".", "_data" ]
[ 254, 4 ]
[ 256, 25 ]
python
en
['en', 'en', 'en']
True
ClassificationBatches.__getitem__
(self, key)
Returns one classification batch by given key.
Returns one classification batch by given key.
def __getitem__(self, key): """Returns one classification batch by given key.""" return self._data[key]
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "return", "self", ".", "_data", "[", "key", "]" ]
[ 258, 4 ]
[ 260, 30 ]
python
en
['en', 'en', 'en']
True
ClassificationBatches.init_from_adversarial_batches_write_to_datastore
( self, submissions, adv_batches )
Populates data from adversarial batches and writes to datastore. Args: submissions: instance of CompetitionSubmissions adv_batches: instance of AversarialBatches
Populates data from adversarial batches and writes to datastore.
def init_from_adversarial_batches_write_to_datastore( self, submissions, adv_batches ): """Populates data from adversarial batches and writes to datastore. Args: submissions: instance of CompetitionSubmissions adv_batches: instance of AversarialBatches """ ...
[ "def", "init_from_adversarial_batches_write_to_datastore", "(", "self", ",", "submissions", ",", "adv_batches", ")", ":", "# prepare classification batches", "idx", "=", "0", "for", "s_id", "in", "iterkeys", "(", "submissions", ".", "defenses", ")", ":", "for", "adv...
[ 262, 4 ]
[ 292, 33 ]
python
en
['en', 'en', 'en']
True
ClassificationBatches.init_from_datastore
(self)
Initializes data by reading it from the datastore.
Initializes data by reading it from the datastore.
def init_from_datastore(self): """Initializes data by reading it from the datastore.""" self._data = {} client = self._datastore_client for entity in client.query_fetch(kind=KIND_CLASSIFICATION_BATCH): class_batch_id = entity.key.flat_path[-1] self.data[class_batc...
[ "def", "init_from_datastore", "(", "self", ")", ":", "self", ".", "_data", "=", "{", "}", "client", "=", "self", ".", "_datastore_client", "for", "entity", "in", "client", ".", "query_fetch", "(", "kind", "=", "KIND_CLASSIFICATION_BATCH", ")", ":", "class_ba...
[ 294, 4 ]
[ 300, 52 ]
python
en
['en', 'en', 'en']
True
ClassificationBatches.read_batch_from_datastore
(self, class_batch_id)
Reads and returns single batch from the datastore.
Reads and returns single batch from the datastore.
def read_batch_from_datastore(self, class_batch_id): """Reads and returns single batch from the datastore.""" client = self._datastore_client key = client.key(KIND_CLASSIFICATION_BATCH, class_batch_id) result = client.get(key) if result is not None: return dict(result...
[ "def", "read_batch_from_datastore", "(", "self", ",", "class_batch_id", ")", ":", "client", "=", "self", ".", "_datastore_client", "key", "=", "client", ".", "key", "(", "KIND_CLASSIFICATION_BATCH", ",", "class_batch_id", ")", "result", "=", "client", ".", "get"...
[ 302, 4 ]
[ 310, 86 ]
python
en
['en', 'en', 'en']
True
ClassificationBatches.compute_classification_results
( self, adv_batches, dataset_batches, dataset_meta, defense_work=None )
Computes classification results. Args: adv_batches: instance of AversarialBatches dataset_batches: instance of DatasetBatches dataset_meta: instance of DatasetMetadata defense_work: instance of DefenseWorkPieces Returns: accuracy_matrix, error_matrix, ...
Computes classification results.
def compute_classification_results( self, adv_batches, dataset_batches, dataset_meta, defense_work=None ): """Computes classification results. Args: adv_batches: instance of AversarialBatches dataset_batches: instance of DatasetBatches dataset_meta: instance of...
[ "def", "compute_classification_results", "(", "self", ",", "adv_batches", ",", "dataset_batches", ",", "dataset_meta", ",", "defense_work", "=", "None", ")", ":", "class_batch_to_work", "=", "{", "}", "if", "defense_work", ":", "for", "v", "in", "itervalues", "(...
[ 312, 4 ]
[ 401, 9 ]
python
en
['en', 'en', 'en']
True
ClassificationBatches.__str__
(self)
Returns human readable string representation, useful for debugging.
Returns human readable string representation, useful for debugging.
def __str__(self): """Returns human readable string representation, useful for debugging.""" buf = StringIO() for idx, (class_batch_id, class_val) in enumerate(iteritems(self.data)): if idx >= TO_STR_MAX_BATCHES: buf.write(u" ...\n") break ...
[ "def", "__str__", "(", "self", ")", ":", "buf", "=", "StringIO", "(", ")", "for", "idx", ",", "(", "class_batch_id", ",", "class_val", ")", "in", "enumerate", "(", "iteritems", "(", "self", ".", "data", ")", ")", ":", "if", "idx", ">=", "TO_STR_MAX_B...
[ 403, 4 ]
[ 412, 29 ]
python
en
['en', 'id', 'en']
True
_check_test_runner
(app_configs=None, **kwargs)
Checks if the user has *not* overridden the ``TEST_RUNNER`` setting & warns them about the default behavior changes. If the user has overridden that setting, we presume they know what they're doing & avoid generating a message.
Checks if the user has *not* overridden the ``TEST_RUNNER`` setting & warns them about the default behavior changes.
def _check_test_runner(app_configs=None, **kwargs): """ Checks if the user has *not* overridden the ``TEST_RUNNER`` setting & warns them about the default behavior changes. If the user has overridden that setting, we presume they know what they're doing & avoid generating a message. """ fro...
[ "def", "_check_test_runner", "(", "app_configs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "django", ".", "conf", "import", "settings", "# We need to establish if this is a project defined on the 1.5 project template,", "# because if the project was generated on t...
[ 16, 0 ]
[ 87, 17 ]
python
en
['en', 'error', 'th']
False
_check_boolean_field_default_value
(app_configs=None, **kwargs)
Checks if there are any BooleanFields without a default value, & warns the user that the default has changed from False to None.
Checks if there are any BooleanFields without a default value, & warns the user that the default has changed from False to None.
def _check_boolean_field_default_value(app_configs=None, **kwargs): """ Checks if there are any BooleanFields without a default value, & warns the user that the default has changed from False to None. """ from django.db import models problem_fields = [ field for model in apps.ge...
[ "def", "_check_boolean_field_default_value", "(", "app_configs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "django", ".", "db", "import", "models", "problem_fields", "=", "[", "field", "for", "model", "in", "apps", ".", "get_models", "(", "*", ...
[ 90, 0 ]
[ 115, 5 ]
python
en
['en', 'error', 'th']
False
parse_uri
(uri)
Parses a URI using the regex given in Appendix B of RFC 3986. (scheme, authority, path, query, fragment) = parse_uri(uri)
Parses a URI using the regex given in Appendix B of RFC 3986.
def parse_uri(uri): """Parses a URI using the regex given in Appendix B of RFC 3986. (scheme, authority, path, query, fragment) = parse_uri(uri) """ groups = URI.match(uri).groups() return (groups[1], groups[3], groups[4], groups[6], groups[8])
[ "def", "parse_uri", "(", "uri", ")", ":", "groups", "=", "URI", ".", "match", "(", "uri", ")", ".", "groups", "(", ")", "return", "(", "groups", "[", "1", "]", ",", "groups", "[", "3", "]", ",", "groups", "[", "4", "]", ",", "groups", "[", "6...
[ 20, 0 ]
[ 26, 66 ]
python
en
['en', 'en', 'en']
True
CacheController._urlnorm
(cls, uri)
Normalize the URL to create a safe key for the cache
Normalize the URL to create a safe key for the cache
def _urlnorm(cls, uri): """Normalize the URL to create a safe key for the cache""" (scheme, authority, path, query, fragment) = parse_uri(uri) if not scheme or not authority: raise Exception("Only absolute URIs are allowed. uri = %s" % uri) scheme = scheme.lower() au...
[ "def", "_urlnorm", "(", "cls", ",", "uri", ")", ":", "(", "scheme", ",", "authority", ",", "path", ",", "query", ",", "fragment", ")", "=", "parse_uri", "(", "uri", ")", "if", "not", "scheme", "or", "not", "authority", ":", "raise", "Exception", "(",...
[ 42, 4 ]
[ 59, 25 ]
python
en
['en', 'en', 'en']
True
CacheController.cached_request
(self, request)
Return a cached response if it exists in the cache, otherwise return False.
Return a cached response if it exists in the cache, otherwise return False.
def cached_request(self, request): """ Return a cached response if it exists in the cache, otherwise return False. """ cache_url = self.cache_url(request.url) logger.debug('Looking up "%s" in the cache', cache_url) cc = self.parse_cache_control(request.headers) ...
[ "def", "cached_request", "(", "self", ",", "request", ")", ":", "cache_url", "=", "self", ".", "cache_url", "(", "request", ".", "url", ")", "logger", ".", "debug", "(", "'Looking up \"%s\" in the cache'", ",", "cache_url", ")", "cc", "=", "self", ".", "pa...
[ 119, 4 ]
[ 228, 20 ]
python
en
['en', 'error', 'th']
False
CacheController.cache_response
(self, request, response, body=None, status_codes=None)
Algorithm for caching requests. This assumes a requests Response object.
Algorithm for caching requests.
def cache_response(self, request, response, body=None, status_codes=None): """ Algorithm for caching requests. This assumes a requests Response object. """ # From httplib2: Don't cache 206's since we aren't going to # handle byte range requests cac...
[ "def", "cache_response", "(", "self", ",", "request", ",", "response", ",", "body", "=", "None", ",", "status_codes", "=", "None", ")", ":", "# From httplib2: Don't cache 206's since we aren't going to", "# handle byte range requests", "cacheable_status_codes",...
[ 246, 4 ]
[ 335, 21 ]
python
en
['en', 'error', 'th']
False
CacheController.update_cached_response
(self, request, response)
On a 304 we will get a new set of headers that we want to update our cached value with, assuming we have one. This should only ever be called when we've sent an ETag and gotten a 304 as the response.
On a 304 we will get a new set of headers that we want to update our cached value with, assuming we have one.
def update_cached_response(self, request, response): """On a 304 we will get a new set of headers that we want to update our cached value with, assuming we have one. This should only ever be called when we've sent an ETag and gotten a 304 as the response. """ cache_url =...
[ "def", "update_cached_response", "(", "self", ",", "request", ",", "response", ")", ":", "cache_url", "=", "self", ".", "cache_url", "(", "request", ".", "url", ")", "cached_response", "=", "self", ".", "serializer", ".", "loads", "(", "request", ",", "sel...
[ 337, 4 ]
[ 375, 30 ]
python
en
['en', 'en', 'en']
True
AbstractProvider.identify
(self, dependency)
Given a dependency, return an identifier for it. This is used in many places to identify the dependency, e.g. whether two requirements should have their specifier parts merged, whether two specifications would conflict with each other (because they the same name but different versions)....
Given a dependency, return an identifier for it.
def identify(self, dependency): """Given a dependency, return an identifier for it. This is used in many places to identify the dependency, e.g. whether two requirements should have their specifier parts merged, whether two specifications would conflict with each other (because they the...
[ "def", "identify", "(", "self", ",", "dependency", ")", ":", "raise", "NotImplementedError" ]
[ 4, 4 ]
[ 12, 33 ]
python
en
['en', 'en', 'en']
True
AbstractProvider.get_preference
(self, resolution, candidates, information)
Produce a sort key for given specification based on preference. The preference is defined as "I think this requirement should be resolved first". The lower the return value is, the more preferred this group of arguments is. :param resolution: Currently pinned candidate, or `None`. ...
Produce a sort key for given specification based on preference.
def get_preference(self, resolution, candidates, information): """Produce a sort key for given specification based on preference. The preference is defined as "I think this requirement should be resolved first". The lower the return value is, the more preferred this group of arguments i...
[ "def", "get_preference", "(", "self", ",", "resolution", ",", "candidates", ",", "information", ")", ":", "raise", "NotImplementedError" ]
[ 14, 4 ]
[ 48, 33 ]
python
en
['en', 'en', 'en']
True
AbstractProvider.find_matches
(self, requirement)
Find all possible candidates that satisfy a requirement. This should try to get candidates based on the requirement's type. For VCS, local, and archive requirements, the one-and-only match is returned, and for a "named" requirement, the index(es) should be consulted to find concrete can...
Find all possible candidates that satisfy a requirement.
def find_matches(self, requirement): """Find all possible candidates that satisfy a requirement. This should try to get candidates based on the requirement's type. For VCS, local, and archive requirements, the one-and-only match is returned, and for a "named" requirement, the index(es) ...
[ "def", "find_matches", "(", "self", ",", "requirement", ")", ":", "raise", "NotImplementedError" ]
[ 50, 4 ]
[ 62, 33 ]
python
en
['en', 'en', 'en']
True
AbstractProvider.is_satisfied_by
(self, requirement, candidate)
Whether the given requirement can be satisfied by a candidate. A boolean should be returned to indicate whether `candidate` is a viable solution to the requirement.
Whether the given requirement can be satisfied by a candidate.
def is_satisfied_by(self, requirement, candidate): """Whether the given requirement can be satisfied by a candidate. A boolean should be returned to indicate whether `candidate` is a viable solution to the requirement. """ raise NotImplementedError
[ "def", "is_satisfied_by", "(", "self", ",", "requirement", ",", "candidate", ")", ":", "raise", "NotImplementedError" ]
[ 64, 4 ]
[ 70, 33 ]
python
en
['en', 'en', 'en']
True
AbstractProvider.get_dependencies
(self, candidate)
Get dependencies of a candidate. This should return a collection of requirements that `candidate` specifies as its dependencies.
Get dependencies of a candidate.
def get_dependencies(self, candidate): """Get dependencies of a candidate. This should return a collection of requirements that `candidate` specifies as its dependencies. """ raise NotImplementedError
[ "def", "get_dependencies", "(", "self", ",", "candidate", ")", ":", "raise", "NotImplementedError" ]
[ 72, 4 ]
[ 78, 33 ]
python
en
['en', 'en', 'en']
True
AbstractResolver.resolve
(self, requirements, **kwargs)
Take a collection of constraints, spit out the resolution result. Parameters ---------- requirements : Collection A collection of constraints kwargs : optional Additional keyword arguments that subclasses may accept. Raises ------ self.ba...
Take a collection of constraints, spit out the resolution result.
def resolve(self, requirements, **kwargs): """Take a collection of constraints, spit out the resolution result. Parameters ---------- requirements : Collection A collection of constraints kwargs : optional Additional keyword arguments that subclasses may ...
[ "def", "resolve", "(", "self", ",", "requirements", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError" ]
[ 91, 4 ]
[ 120, 33 ]
python
en
['en', 'en', 'en']
True
query_for_ids
(query: QuerySet, user_ids: List[int], field: str)
This function optimizes searches of the form `user_profile_id in (1, 2, 3, 4)` by quickly building the where clauses. Profiling shows significant speedups over the normal Django-based approach. Use this very carefully! Also, the caller should guard against empty lists of user_ids.
This function optimizes searches of the form `user_profile_id in (1, 2, 3, 4)` by quickly building the where clauses. Profiling shows significant speedups over the normal Django-based approach.
def query_for_ids(query: QuerySet, user_ids: List[int], field: str) -> QuerySet: """ This function optimizes searches of the form `user_profile_id in (1, 2, 3, 4)` by quickly building the where clauses. Profiling shows significant speedups over the normal Django-based approach. Use this very c...
[ "def", "query_for_ids", "(", "query", ":", "QuerySet", ",", "user_ids", ":", "List", "[", "int", "]", ",", "field", ":", "str", ")", "->", "QuerySet", ":", "assert", "user_ids", "clause", "=", "f\"{field} IN %s\"", "query", "=", "query", ".", "extra", "(...
[ 100, 0 ]
[ 116, 16 ]
python
en
['en', 'error', 'th']
False
get_display_recipient_by_id
( recipient_id: int, recipient_type: int, recipient_type_id: Optional[int] )
returns: an object describing the recipient (using a cache). If the type is a stream, the type_id must be an int; a string is returned. Otherwise, type_id may be None; an array of recipient dicts is returned.
returns: an object describing the recipient (using a cache). If the type is a stream, the type_id must be an int; a string is returned. Otherwise, type_id may be None; an array of recipient dicts is returned.
def get_display_recipient_by_id( recipient_id: int, recipient_type: int, recipient_type_id: Optional[int] ) -> DisplayRecipientT: """ returns: an object describing the recipient (using a cache). If the type is a stream, the type_id must be an int; a string is returned. Otherwise, type_id may be None...
[ "def", "get_display_recipient_by_id", "(", "recipient_id", ":", "int", ",", "recipient_type", ":", "int", ",", "recipient_type_id", ":", "Optional", "[", "int", "]", ")", "->", "DisplayRecipientT", ":", "# Have to import here, to avoid circular dependency.", "from", "ze...
[ 130, 0 ]
[ 144, 60 ]
python
en
['en', 'error', 'th']
False
realm_filters_for_realm
(realm_id: int)
Processes data from `linkifiers_for_realm` to return to older clients, which use the `realm_filters` events.
Processes data from `linkifiers_for_realm` to return to older clients, which use the `realm_filters` events.
def realm_filters_for_realm(realm_id: int) -> List[Tuple[str, str, int]]: """ Processes data from `linkifiers_for_realm` to return to older clients, which use the `realm_filters` events. """ linkifiers = linkifiers_for_realm(realm_id) realm_filters: List[Tuple[str, str, int]] = [] for linkif...
[ "def", "realm_filters_for_realm", "(", "realm_id", ":", "int", ")", "->", "List", "[", "Tuple", "[", "str", ",", "str", ",", "int", "]", "]", ":", "linkifiers", "=", "linkifiers_for_realm", "(", "realm_id", ")", "realm_filters", ":", "List", "[", "Tuple", ...
[ 912, 0 ]
[ 921, 24 ]
python
en
['en', 'error', 'th']
False
get_active_streams
(realm: Optional[Realm])
Return all streams (including invite-only streams) that have not been deactivated.
Return all streams (including invite-only streams) that have not been deactivated.
def get_active_streams(realm: Optional[Realm]) -> QuerySet: # TODO: Change return type to QuerySet[Stream] # NOTE: Return value is used as a QuerySet, so cannot currently be Sequence[QuerySet] """ Return all streams (including invite-only streams) that have not been deactivated. """ return Strea...
[ "def", "get_active_streams", "(", "realm", ":", "Optional", "[", "Realm", "]", ")", "->", "QuerySet", ":", "# TODO: Change return type to QuerySet[Stream]", "# NOTE: Return value is used as a QuerySet, so cannot currently be Sequence[QuerySet]", "return", "Stream", ".", "objects"...
[ 1959, 0 ]
[ 1965, 64 ]
python
en
['en', 'error', 'th']
False
get_stream
(stream_name: str, realm: Realm)
Callers that don't have a Realm object already available should use get_realm_stream directly, to avoid unnecessarily fetching the Realm object.
Callers that don't have a Realm object already available should use get_realm_stream directly, to avoid unnecessarily fetching the Realm object.
def get_stream(stream_name: str, realm: Realm) -> Stream: """ Callers that don't have a Realm object already available should use get_realm_stream directly, to avoid unnecessarily fetching the Realm object. """ return get_realm_stream(stream_name, realm.id)
[ "def", "get_stream", "(", "stream_name", ":", "str", ",", "realm", ":", "Realm", ")", "->", "Stream", ":", "return", "get_realm_stream", "(", "stream_name", ",", "realm", ".", "id", ")" ]
[ 1968, 0 ]
[ 1974, 50 ]
python
en
['en', 'error', 'th']
False
bulk_get_huddle_user_ids
(recipients: List[Recipient])
Takes a list of huddle-type recipients, returns a dict mapping recipient id to list of user ids in the huddle.
Takes a list of huddle-type recipients, returns a dict mapping recipient id to list of user ids in the huddle.
def bulk_get_huddle_user_ids(recipients: List[Recipient]) -> Dict[int, List[int]]: """ Takes a list of huddle-type recipients, returns a dict mapping recipient id to list of user ids in the huddle. """ assert all(recipient.type == Recipient.HUDDLE for recipient in recipients) if not recipients: ...
[ "def", "bulk_get_huddle_user_ids", "(", "recipients", ":", "List", "[", "Recipient", "]", ")", "->", "Dict", "[", "int", ",", "List", "[", "int", "]", "]", ":", "assert", "all", "(", "recipient", ".", "type", "==", "Recipient", ".", "HUDDLE", "for", "r...
[ 2036, 0 ]
[ 2057, 22 ]
python
en
['en', 'error', 'th']
False
Realm.authentication_methods_dict
(self)
Returns the a mapping from authentication flags to their status, showing only those authentication flags that are supported on the current server (i.e. if EmailAuthBackend is not configured on the server, this will not return an entry for "Email").
Returns the a mapping from authentication flags to their status, showing only those authentication flags that are supported on the current server (i.e. if EmailAuthBackend is not configured on the server, this will not return an entry for "Email").
def authentication_methods_dict(self) -> Dict[str, bool]: """Returns the a mapping from authentication flags to their status, showing only those authentication flags that are supported on the current server (i.e. if EmailAuthBackend is not configured on the server, this will not return a...
[ "def", "authentication_methods_dict", "(", "self", ")", "->", "Dict", "[", "str", ",", "bool", "]", ":", "# This mapping needs to be imported from here due to the cyclic", "# dependency.", "from", "zproject", ".", "backends", "import", "AUTH_BACKEND_NAME_MAP", "ret", ":",...
[ 530, 4 ]
[ 548, 18 ]
python
en
['en', 'en', 'en']
True
Realm.get_admin_users_and_bots
( self, include_realm_owners: bool = True )
Use this in contexts where we want administrative users as well as bots with administrator privileges, like send_event calls for notifications to all administrator users.
Use this in contexts where we want administrative users as well as bots with administrator privileges, like send_event calls for notifications to all administrator users.
def get_admin_users_and_bots( self, include_realm_owners: bool = True ) -> Sequence["UserProfile"]: """Use this in contexts where we want administrative users as well as bots with administrator privileges, like send_event calls for notifications to all administrator users. ""...
[ "def", "get_admin_users_and_bots", "(", "self", ",", "include_realm_owners", ":", "bool", "=", "True", ")", "->", "Sequence", "[", "\"UserProfile\"", "]", ":", "if", "include_realm_owners", ":", "roles", "=", "[", "UserProfile", ".", "ROLE_REALM_ADMINISTRATOR", ",...
[ 561, 4 ]
[ 578, 9 ]
python
en
['en', 'en', 'en']
True
Realm.get_human_admin_users
(self, include_realm_owners: bool = True)
Use this in contexts where we want only human users with administrative privileges, like sending an email to all of a realm's administrators (bots don't have real email addresses).
Use this in contexts where we want only human users with administrative privileges, like sending an email to all of a realm's administrators (bots don't have real email addresses).
def get_human_admin_users(self, include_realm_owners: bool = True) -> QuerySet: """Use this in contexts where we want only human users with administrative privileges, like sending an email to all of a realm's administrators (bots don't have real email addresses). """ if include_r...
[ "def", "get_human_admin_users", "(", "self", ",", "include_realm_owners", ":", "bool", "=", "True", ")", "->", "QuerySet", ":", "if", "include_realm_owners", ":", "roles", "=", "[", "UserProfile", ".", "ROLE_REALM_ADMINISTRATOR", ",", "UserProfile", ".", "ROLE_REA...
[ 580, 4 ]
[ 596, 9 ]
python
en
['en', 'en', 'en']
True
Realm.display_subdomain
(self)
Likely to be temporary function to avoid signup messages being sent to an empty topic
Likely to be temporary function to avoid signup messages being sent to an empty topic
def display_subdomain(self) -> str: """Likely to be temporary function to avoid signup messages being sent to an empty topic""" if self.string_id == "": return "." return self.string_id
[ "def", "display_subdomain", "(", "self", ")", "->", "str", ":", "if", "self", ".", "string_id", "==", "\"\"", ":", "return", "\".\"", "return", "self", ".", "string_id" ]
[ 664, 4 ]
[ 669, 29 ]
python
en
['en', 'en', 'en']
True
UserProfile.can_admin_user
(self, target_user: "UserProfile")
Returns whether this user has permission to modify target_user
Returns whether this user has permission to modify target_user
def can_admin_user(self, target_user: "UserProfile") -> bool: """Returns whether this user has permission to modify target_user""" if target_user.bot_owner == self: return True elif self.is_realm_admin and self.realm == target_user.realm: return True else: ...
[ "def", "can_admin_user", "(", "self", ",", "target_user", ":", "\"UserProfile\"", ")", "->", "bool", ":", "if", "target_user", ".", "bot_owner", "==", "self", ":", "return", "True", "elif", "self", ".", "is_realm_admin", "and", "self", ".", "realm", "==", ...
[ 1417, 4 ]
[ 1424, 24 ]
python
en
['en', 'en', 'en']
True
Message.topic_name
(self)
Please start using this helper to facilitate an eventual switch over to a separate topic table.
Please start using this helper to facilitate an eventual switch over to a separate topic table.
def topic_name(self) -> str: """ Please start using this helper to facilitate an eventual switch over to a separate topic table. """ return self.subject
[ "def", "topic_name", "(", "self", ")", "->", "str", ":", "return", "self", ".", "subject" ]
[ 2137, 4 ]
[ 2142, 27 ]
python
en
['en', 'error', 'th']
False
Message.is_stream_message
(self)
Find out whether a message is a stream message by looking up its recipient.type. TODO: Make this an easier operation by denormalizing the message type onto Message, either explicitly (message.type) or implicitly (message.stream_id is not None).
Find out whether a message is a stream message by looking up its recipient.type. TODO: Make this an easier operation by denormalizing the message type onto Message, either explicitly (message.type) or implicitly (message.stream_id is not None).
def is_stream_message(self) -> bool: """ Find out whether a message is a stream message by looking up its recipient.type. TODO: Make this an easier operation by denormalizing the message type onto Message, either explicitly (message.type) or implicitly (message.stream_id...
[ "def", "is_stream_message", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "recipient", ".", "type", "==", "Recipient", ".", "STREAM" ]
[ 2147, 4 ]
[ 2155, 54 ]
python
en
['en', 'error', 'th']
False
Message.sent_by_human
(self)
Used to determine whether a message was sent by a full Zulip UI style client (and thus whether the message should be treated as sent by a human and automatically marked as read for the sender). The purpose of this distinction is to ensure that message sent to the user by e.g. a Google C...
Used to determine whether a message was sent by a full Zulip UI style client (and thus whether the message should be treated as sent by a human and automatically marked as read for the sender). The purpose of this distinction is to ensure that message sent to the user by e.g. a Google C...
def sent_by_human(self) -> bool: """Used to determine whether a message was sent by a full Zulip UI style client (and thus whether the message should be treated as sent by a human and automatically marked as read for the sender). The purpose of this distinction is to ensure that ...
[ "def", "sent_by_human", "(", "self", ")", "->", "bool", ":", "sending_client", "=", "self", ".", "sending_client", ".", "name", ".", "lower", "(", ")", "return", "(", "sending_client", "in", "(", "\"zulipandroid\"", ",", "\"zulipios\"", ",", "\"zulipdesktop\""...
[ 2175, 4 ]
[ 2200, 46 ]
python
en
['en', 'en', 'en']
True
Message.is_status_message
(content: str, rendered_content: str)
"status messages" start with /me and have special rendering: /me loves chocolate -> Full Name loves chocolate
"status messages" start with /me and have special rendering: /me loves chocolate -> Full Name loves chocolate
def is_status_message(content: str, rendered_content: str) -> bool: """ "status messages" start with /me and have special rendering: /me loves chocolate -> Full Name loves chocolate """ if content.startswith("/me "): return True return False
[ "def", "is_status_message", "(", "content", ":", "str", ",", "rendered_content", ":", "str", ")", "->", "bool", ":", "if", "content", ".", "startswith", "(", "\"/me \"", ")", ":", "return", "True", "return", "False" ]
[ 2203, 4 ]
[ 2210, 20 ]
python
en
['en', 'error', 'th']
False
AbstractUserMessage.flags_list_for_flags
(val: int)
This function is highly optimized, because it actually slows down sending messages in a naive implementation.
This function is highly optimized, because it actually slows down sending messages in a naive implementation.
def flags_list_for_flags(val: int) -> List[str]: """ This function is highly optimized, because it actually slows down sending messages in a naive implementation. """ flags = [] mask = 1 for flag in UserMessage.ALL_FLAGS: if (val & mask) and flag not i...
[ "def", "flags_list_for_flags", "(", "val", ":", "int", ")", "->", "List", "[", "str", "]", ":", "flags", "=", "[", "]", "mask", "=", "1", "for", "flag", "in", "UserMessage", ".", "ALL_FLAGS", ":", "if", "(", "val", "&", "mask", ")", "and", "flag", ...
[ 2473, 4 ]
[ 2484, 20 ]
python
en
['en', 'error', 'th']
False
Deserializer
(object_list, **options)
Deserialize simple Python objects back into Django ORM instances. It's expected that you pass the Python objects themselves (instead of a stream or a string) to the constructor
Deserialize simple Python objects back into Django ORM instances.
def Deserializer(object_list, **options): """ Deserialize simple Python objects back into Django ORM instances. It's expected that you pass the Python objects themselves (instead of a stream or a string) to the constructor """ db = options.pop('using', DEFAULT_DB_ALIAS) ignore = options.pop...
[ "def", "Deserializer", "(", "object_list", ",", "*", "*", "options", ")", ":", "db", "=", "options", ".", "pop", "(", "'using'", ",", "DEFAULT_DB_ALIAS", ")", "ignore", "=", "options", ".", "pop", "(", "'ignorenonexistent'", ",", "False", ")", "for", "d"...
[ 80, 0 ]
[ 155, 52 ]
python
en
['en', 'error', 'th']
False
_get_model
(model_identifier)
Helper to look up a model from an "app_label.model_name" string.
Helper to look up a model from an "app_label.model_name" string.
def _get_model(model_identifier): """ Helper to look up a model from an "app_label.model_name" string. """ try: return apps.get_model(model_identifier) except (LookupError, TypeError): raise base.DeserializationError("Invalid model identifier: '%s'" % model_identifier)
[ "def", "_get_model", "(", "model_identifier", ")", ":", "try", ":", "return", "apps", ".", "get_model", "(", "model_identifier", ")", "except", "(", "LookupError", ",", "TypeError", ")", ":", "raise", "base", ".", "DeserializationError", "(", "\"Invalid model id...
[ 158, 0 ]
[ 165, 92 ]
python
en
['en', 'error', 'th']
False
Command.__init__
(self, dist)
Create and initialize a new Command object. Most importantly, invokes the 'initialize_options()' method, which is the real initializer and depends on the actual command being instantiated.
Create and initialize a new Command object. Most importantly, invokes the 'initialize_options()' method, which is the real initializer and depends on the actual command being instantiated.
def __init__(self, dist): """Create and initialize a new Command object. Most importantly, invokes the 'initialize_options()' method, which is the real initializer and depends on the actual command being instantiated. """ # late import because of mutual dependence betwee...
[ "def", "__init__", "(", "self", ",", "dist", ")", ":", "# late import because of mutual dependence between these classes", "from", "distutils", ".", "dist", "import", "Distribution", "if", "not", "isinstance", "(", "dist", ",", "Distribution", ")", ":", "raise", "Ty...
[ 46, 4 ]
[ 91, 26 ]
python
en
['en', 'en', 'en']
True
Command.initialize_options
(self)
Set default values for all the options that this command supports. Note that these defaults may be overridden by other commands, by the setup script, by config files, or by the command-line. Thus, this is not the place to code dependencies between options; generally, 'initialize_option...
Set default values for all the options that this command supports. Note that these defaults may be overridden by other commands, by the setup script, by config files, or by the command-line. Thus, this is not the place to code dependencies between options; generally, 'initialize_option...
def initialize_options(self): """Set default values for all the options that this command supports. Note that these defaults may be overridden by other commands, by the setup script, by config files, or by the command-line. Thus, this is not the place to code dependencies betwe...
[ "def", "initialize_options", "(", "self", ")", ":", "raise", "RuntimeError", "(", "\"abstract method -- subclass %s must override\"", "%", "self", ".", "__class__", ")" ]
[ 122, 4 ]
[ 133, 44 ]
python
en
['en', 'en', 'en']
True
Command.finalize_options
(self)
Set final values for all the options that this command supports. This is always called as late as possible, ie. after any option assignments from the command-line or from other commands have been done. Thus, this is the place to code option dependencies: if 'foo' depends on 'bar', then...
Set final values for all the options that this command supports. This is always called as late as possible, ie. after any option assignments from the command-line or from other commands have been done. Thus, this is the place to code option dependencies: if 'foo' depends on 'bar', then...
def finalize_options(self): """Set final values for all the options that this command supports. This is always called as late as possible, ie. after any option assignments from the command-line or from other commands have been done. Thus, this is the place to code option dependencies: ...
[ "def", "finalize_options", "(", "self", ")", ":", "raise", "RuntimeError", "(", "\"abstract method -- subclass %s must override\"", "%", "self", ".", "__class__", ")" ]
[ 135, 4 ]
[ 147, 44 ]
python
en
['en', 'en', 'en']
True
Command.run
(self)
A command's raison d'etre: carry out the action it exists to perform, controlled by the options initialized in 'initialize_options()', customized by other commands, the setup script, the command-line, and config files, and finalized in 'finalize_options()'. All terminal output and files...
A command's raison d'etre: carry out the action it exists to perform, controlled by the options initialized in 'initialize_options()', customized by other commands, the setup script, the command-line, and config files, and finalized in 'finalize_options()'. All terminal output and files...
def run(self): """A command's raison d'etre: carry out the action it exists to perform, controlled by the options initialized in 'initialize_options()', customized by other commands, the setup script, the command-line, and config files, and finalized in 'finalize_options()'. All...
[ "def", "run", "(", "self", ")", ":", "raise", "RuntimeError", "(", "\"abstract method -- subclass %s must override\"", "%", "self", ".", "__class__", ")" ]
[ 164, 4 ]
[ 175, 44 ]
python
en
['en', 'fr', 'en']
True
Command.announce
(self, msg, level=1)
If the current verbosity level is of greater than or equal to 'level' print 'msg' to stdout.
If the current verbosity level is of greater than or equal to 'level' print 'msg' to stdout.
def announce(self, msg, level=1): """If the current verbosity level is of greater than or equal to 'level' print 'msg' to stdout. """ log.log(level, msg)
[ "def", "announce", "(", "self", ",", "msg", ",", "level", "=", "1", ")", ":", "log", ".", "log", "(", "level", ",", "msg", ")" ]
[ 177, 4 ]
[ 181, 27 ]
python
en
['en', 'en', 'en']
True
Command.debug_print
(self, msg)
Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true.
Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true.
def debug_print(self, msg): """Print 'msg' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true. """ from distutils.debug import DEBUG if DEBUG: print(msg) sys.stdout.flush()
[ "def", "debug_print", "(", "self", ",", "msg", ")", ":", "from", "distutils", ".", "debug", "import", "DEBUG", "if", "DEBUG", ":", "print", "(", "msg", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
[ 183, 4 ]
[ 190, 30 ]
python
en
['en', 'en', 'en']
True
Command.ensure_string
(self, option, default=None)
Ensure that 'option' is a string; if not defined, set it to 'default'.
Ensure that 'option' is a string; if not defined, set it to 'default'.
def ensure_string(self, option, default=None): """Ensure that 'option' is a string; if not defined, set it to 'default'. """ self._ensure_stringlike(option, "string", default)
[ "def", "ensure_string", "(", "self", ",", "option", ",", "default", "=", "None", ")", ":", "self", ".", "_ensure_stringlike", "(", "option", ",", "\"string\"", ",", "default", ")" ]
[ 216, 4 ]
[ 220, 58 ]
python
en
['en', 'en', 'en']
True
Command.ensure_string_list
(self, option)
r"""Ensure that 'option' is a list of strings. If 'option' is currently a string, we split it either on /,\s*/ or /\s+/, so "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become ["foo", "bar", "baz"].
r"""Ensure that 'option' is a list of strings. If 'option' is currently a string, we split it either on /,\s*/ or /\s+/, so "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become ["foo", "bar", "baz"].
def ensure_string_list(self, option): r"""Ensure that 'option' is a list of strings. If 'option' is currently a string, we split it either on /,\s*/ or /\s+/, so "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become ["foo", "bar", "baz"]. """ val = getattr(self, ...
[ "def", "ensure_string_list", "(", "self", ",", "option", ")", ":", "val", "=", "getattr", "(", "self", ",", "option", ")", "if", "val", "is", "None", ":", "return", "elif", "isinstance", "(", "val", ",", "str", ")", ":", "setattr", "(", "self", ",", ...
[ 222, 4 ]
[ 241, 38 ]
python
en
['en', 'en', 'en']
True
Command.ensure_filename
(self, option)
Ensure that 'option' is the name of an existing file.
Ensure that 'option' is the name of an existing file.
def ensure_filename(self, option): """Ensure that 'option' is the name of an existing file.""" self._ensure_tested_string(option, os.path.isfile, "filename", "'%s' does not exist or is not a file")
[ "def", "ensure_filename", "(", "self", ",", "option", ")", ":", "self", ".", "_ensure_tested_string", "(", "option", ",", "os", ".", "path", ".", "isfile", ",", "\"filename\"", ",", "\"'%s' does not exist or is not a file\"", ")" ]
[ 250, 4 ]
[ 254, 74 ]
python
en
['en', 'en', 'en']
True
Command.set_undefined_options
(self, src_cmd, *option_pairs)
Set the values of any "undefined" options from corresponding option values in some other command object. "Undefined" here means "is None", which is the convention used to indicate that an option has not been changed between 'initialize_options()' and 'finalize_options()'. Usually calle...
Set the values of any "undefined" options from corresponding option values in some other command object. "Undefined" here means "is None", which is the convention used to indicate that an option has not been changed between 'initialize_options()' and 'finalize_options()'. Usually calle...
def set_undefined_options(self, src_cmd, *option_pairs): """Set the values of any "undefined" options from corresponding option values in some other command object. "Undefined" here means "is None", which is the convention used to indicate that an option has not been changed between 'in...
[ "def", "set_undefined_options", "(", "self", ",", "src_cmd", ",", "*", "option_pairs", ")", ":", "# Option_pairs: list of (src_option, dst_option) tuples", "src_cmd_obj", "=", "self", ".", "distribution", ".", "get_command_obj", "(", "src_cmd", ")", "src_cmd_obj", ".", ...
[ 270, 4 ]
[ 289, 75 ]
python
en
['en', 'en', 'en']
True
Command.get_finalized_command
(self, command, create=1)
Wrapper around Distribution's 'get_command_obj()' method: find (create if necessary and 'create' is true) the command object for 'command', call its 'ensure_finalized()' method, and return the finalized command object.
Wrapper around Distribution's 'get_command_obj()' method: find (create if necessary and 'create' is true) the command object for 'command', call its 'ensure_finalized()' method, and return the finalized command object.
def get_finalized_command(self, command, create=1): """Wrapper around Distribution's 'get_command_obj()' method: find (create if necessary and 'create' is true) the command object for 'command', call its 'ensure_finalized()' method, and return the finalized command object. """ ...
[ "def", "get_finalized_command", "(", "self", ",", "command", ",", "create", "=", "1", ")", ":", "cmd_obj", "=", "self", ".", "distribution", ".", "get_command_obj", "(", "command", ",", "create", ")", "cmd_obj", ".", "ensure_finalized", "(", ")", "return", ...
[ 291, 4 ]
[ 299, 22 ]
python
en
['en', 'de', 'en']
True
Command.run_command
(self, command)
Run some other command: uses the 'run_command()' method of Distribution, which creates and finalizes the command object if necessary and then invokes its 'run()' method.
Run some other command: uses the 'run_command()' method of Distribution, which creates and finalizes the command object if necessary and then invokes its 'run()' method.
def run_command(self, command): """Run some other command: uses the 'run_command()' method of Distribution, which creates and finalizes the command object if necessary and then invokes its 'run()' method. """ self.distribution.run_command(command)
[ "def", "run_command", "(", "self", ",", "command", ")", ":", "self", ".", "distribution", ".", "run_command", "(", "command", ")" ]
[ 307, 4 ]
[ 312, 46 ]
python
en
['en', 'en', 'en']
True
Command.get_sub_commands
(self)
Determine the sub-commands that are relevant in the current distribution (ie., that need to be run). This is based on the 'sub_commands' class attribute: each tuple in that list may include a method that we call to determine if the subcommand needs to be run for the current distribution...
Determine the sub-commands that are relevant in the current distribution (ie., that need to be run). This is based on the 'sub_commands' class attribute: each tuple in that list may include a method that we call to determine if the subcommand needs to be run for the current distribution...
def get_sub_commands(self): """Determine the sub-commands that are relevant in the current distribution (ie., that need to be run). This is based on the 'sub_commands' class attribute: each tuple in that list may include a method that we call to determine if the subcommand needs to be ...
[ "def", "get_sub_commands", "(", "self", ")", ":", "commands", "=", "[", "]", "for", "(", "cmd_name", ",", "method", ")", "in", "self", ".", "sub_commands", ":", "if", "method", "is", "None", "or", "method", "(", "self", ")", ":", "commands", ".", "ap...
[ 314, 4 ]
[ 325, 23 ]
python
en
['en', 'en', 'en']
True
Command.copy_file
(self, infile, outfile, preserve_mode=1, preserve_times=1, link=None, level=1)
Copy a file respecting verbose, dry-run and force flags. (The former two default to whatever is in the Distribution object, and the latter defaults to false for commands that don't define it.)
Copy a file respecting verbose, dry-run and force flags. (The former two default to whatever is in the Distribution object, and the latter defaults to false for commands that don't define it.)
def copy_file(self, infile, outfile, preserve_mode=1, preserve_times=1, link=None, level=1): """Copy a file respecting verbose, dry-run and force flags. (The former two default to whatever is in the Distribution object, and the latter defaults to false for commands that don't ...
[ "def", "copy_file", "(", "self", ",", "infile", ",", "outfile", ",", "preserve_mode", "=", "1", ",", "preserve_times", "=", "1", ",", "link", "=", "None", ",", "level", "=", "1", ")", ":", "return", "file_util", ".", "copy_file", "(", "infile", ",", ...
[ 339, 4 ]
[ 346, 56 ]
python
en
['en', 'en', 'en']
True
Command.copy_tree
(self, infile, outfile, preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1)
Copy an entire directory tree respecting verbose, dry-run, and force flags.
Copy an entire directory tree respecting verbose, dry-run, and force flags.
def copy_tree(self, infile, outfile, preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1): """Copy an entire directory tree respecting verbose, dry-run, and force flags. """ return dir_util.copy_tree(infile, outfile, preserve_mode, ...
[ "def", "copy_tree", "(", "self", ",", "infile", ",", "outfile", ",", "preserve_mode", "=", "1", ",", "preserve_times", "=", "1", ",", "preserve_symlinks", "=", "0", ",", "level", "=", "1", ")", ":", "return", "dir_util", ".", "copy_tree", "(", "infile", ...
[ 348, 4 ]
[ 355, 71 ]
python
en
['en', 'en', 'en']
True
Command.move_file
(self, src, dst, level=1)
Move a file respecting dry-run flag.
Move a file respecting dry-run flag.
def move_file (self, src, dst, level=1): """Move a file respecting dry-run flag.""" return file_util.move_file(src, dst, dry_run=self.dry_run)
[ "def", "move_file", "(", "self", ",", "src", ",", "dst", ",", "level", "=", "1", ")", ":", "return", "file_util", ".", "move_file", "(", "src", ",", "dst", ",", "dry_run", "=", "self", ".", "dry_run", ")" ]
[ 357, 4 ]
[ 359, 66 ]
python
en
['id', 'en', 'en']
True
Command.spawn
(self, cmd, search_path=1, level=1)
Spawn an external command respecting dry-run flag.
Spawn an external command respecting dry-run flag.
def spawn(self, cmd, search_path=1, level=1): """Spawn an external command respecting dry-run flag.""" from distutils.spawn import spawn spawn(cmd, search_path, dry_run=self.dry_run)
[ "def", "spawn", "(", "self", ",", "cmd", ",", "search_path", "=", "1", ",", "level", "=", "1", ")", ":", "from", "distutils", ".", "spawn", "import", "spawn", "spawn", "(", "cmd", ",", "search_path", ",", "dry_run", "=", "self", ".", "dry_run", ")" ]
[ 361, 4 ]
[ 364, 53 ]
python
en
['en', 'lb', 'en']
True
Command.make_file
(self, infiles, outfile, func, args, exec_msg=None, skip_msg=None, level=1)
Special case of 'execute()' for operations that process one or more input files and generate one output file. Works just like 'execute()', except the operation is skipped and a different message printed if 'outfile' already exists and is newer than all files listed in 'infiles'. If the...
Special case of 'execute()' for operations that process one or more input files and generate one output file. Works just like 'execute()', except the operation is skipped and a different message printed if 'outfile' already exists and is newer than all files listed in 'infiles'. If the...
def make_file(self, infiles, outfile, func, args, exec_msg=None, skip_msg=None, level=1): """Special case of 'execute()' for operations that process one or more input files and generate one output file. Works just like 'execute()', except the operation is skipped and a differe...
[ "def", "make_file", "(", "self", ",", "infiles", ",", "outfile", ",", "func", ",", "args", ",", "exec_msg", "=", "None", ",", "skip_msg", "=", "None", ",", "level", "=", "1", ")", ":", "if", "skip_msg", "is", "None", ":", "skip_msg", "=", "\"skipping...
[ 372, 4 ]
[ 402, 31 ]
python
en
['en', 'en', 'en']
True
load_provider_config
()
Initialize the active payment provider config dict Also verifies that all config params the provider requires are present
Initialize the active payment provider config dict
def load_provider_config(): """Initialize the active payment provider config dict Also verifies that all config params the provider requires are present""" global _provider_class # Provider path is the only thing loaded from env # in the global settings, the rest are added here provider_path =...
[ "def", "load_provider_config", "(", ")", ":", "global", "_provider_class", "# Provider path is the only thing loaded from env", "# in the global settings, the rest are added here", "provider_path", "=", "getattr", "(", "settings", ",", "'RESPA_PAYMENTS_PROVIDER_CLASS'", ")", "_prov...
[ 12, 0 ]
[ 35, 35 ]
python
en
['en', 'en', 'en']
True
get_payment_provider
(request: HttpRequest, ui_return_url: str = None)
Get a new instance of the active payment provider with associated request and optional return_url info
Get a new instance of the active payment provider with associated request and optional return_url info
def get_payment_provider(request: HttpRequest, ui_return_url: str = None) -> PaymentProvider: """Get a new instance of the active payment provider with associated request and optional return_url info""" return _provider_class(request=request, ui_return_url=ui_return_url)
[ "def", "get_payment_provider", "(", "request", ":", "HttpRequest", ",", "ui_return_url", ":", "str", "=", "None", ")", "->", "PaymentProvider", ":", "return", "_provider_class", "(", "request", "=", "request", ",", "ui_return_url", "=", "ui_return_url", ")" ]
[ 38, 0 ]
[ 41, 72 ]
python
en
['en', 'en', 'en']
True
ValidationError.__init__
(self, message, code=None, params=None)
The `message` argument can be a single error, a list of errors, or a dictionary that maps field names to lists of errors. What we define as an "error" can be either a simple string or an instance of ValidationError with its message attribute set, and what we define as list or di...
The `message` argument can be a single error, a list of errors, or a dictionary that maps field names to lists of errors. What we define as an "error" can be either a simple string or an instance of ValidationError with its message attribute set, and what we define as list or di...
def __init__(self, message, code=None, params=None): """ The `message` argument can be a single error, a list of errors, or a dictionary that maps field names to lists of errors. What we define as an "error" can be either a simple string or an instance of ValidationError with its...
[ "def", "__init__", "(", "self", ",", "message", ",", "code", "=", "None", ",", "params", "=", "None", ")", ":", "super", "(", ")", ".", "__init__", "(", "message", ",", "code", ",", "params", ")", "if", "isinstance", "(", "message", ",", "ValidationE...
[ 100, 4 ]
[ 141, 36 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.get_connection_params
(self)
Returns a dict of parameters suitable for get_new_connection.
Returns a dict of parameters suitable for get_new_connection.
def get_connection_params(self): """Returns a dict of parameters suitable for get_new_connection.""" raise NotImplementedError('subclasses of BaseDatabaseWrapper may require a get_connection_params() method')
[ "def", "get_connection_params", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseDatabaseWrapper may require a get_connection_params() method'", ")" ]
[ 97, 4 ]
[ 99, 115 ]
python
en
['en', 'en', 'en']
True
BaseDatabaseWrapper.get_new_connection
(self, conn_params)
Opens a connection to the database.
Opens a connection to the database.
def get_new_connection(self, conn_params): """Opens a connection to the database.""" raise NotImplementedError('subclasses of BaseDatabaseWrapper may require a get_new_connection() method')
[ "def", "get_new_connection", "(", "self", ",", "conn_params", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseDatabaseWrapper may require a get_new_connection() method'", ")" ]
[ 101, 4 ]
[ 103, 112 ]
python
en
['en', 'en', 'en']
True
BaseDatabaseWrapper.init_connection_state
(self)
Initializes the database connection settings.
Initializes the database connection settings.
def init_connection_state(self): """Initializes the database connection settings.""" raise NotImplementedError('subclasses of BaseDatabaseWrapper may require an init_connection_state() method')
[ "def", "init_connection_state", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseDatabaseWrapper may require an init_connection_state() method'", ")" ]
[ 105, 4 ]
[ 107, 116 ]
python
en
['en', 'en', 'en']
True
BaseDatabaseWrapper.create_cursor
(self)
Creates a cursor. Assumes that a connection is established.
Creates a cursor. Assumes that a connection is established.
def create_cursor(self): """Creates a cursor. Assumes that a connection is established.""" raise NotImplementedError('subclasses of BaseDatabaseWrapper may require a create_cursor() method')
[ "def", "create_cursor", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseDatabaseWrapper may require a create_cursor() method'", ")" ]
[ 109, 4 ]
[ 111, 107 ]
python
en
['en', 'en', 'en']
True
BaseDatabaseWrapper.connect
(self)
Connects to the database. Assumes that the connection is closed.
Connects to the database. Assumes that the connection is closed.
def connect(self): """Connects to the database. Assumes that the connection is closed.""" # In case the previous connection was closed while in an atomic block self.in_atomic_block = False self.savepoint_ids = [] self.needs_rollback = False # Reset parameters defining whe...
[ "def", "connect", "(", "self", ")", ":", "# In case the previous connection was closed while in an atomic block", "self", ".", "in_atomic_block", "=", "False", "self", ".", "savepoint_ids", "=", "[", "]", "self", ".", "needs_rollback", "=", "False", "# Reset parameters ...
[ 115, 4 ]
[ 131, 71 ]
python
en
['en', 'en', 'en']
True
BaseDatabaseWrapper.ensure_connection
(self)
Guarantees that a connection to the database is established.
Guarantees that a connection to the database is established.
def ensure_connection(self): """ Guarantees that a connection to the database is established. """ if self.connection is None: with self.wrap_database_errors: self.connect()
[ "def", "ensure_connection", "(", "self", ")", ":", "if", "self", ".", "connection", "is", "None", ":", "with", "self", ".", "wrap_database_errors", ":", "self", ".", "connect", "(", ")" ]
[ 133, 4 ]
[ 139, 30 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.cursor
(self)
Creates a cursor, opening a connection if necessary.
Creates a cursor, opening a connection if necessary.
def cursor(self): """ Creates a cursor, opening a connection if necessary. """ self.validate_thread_sharing() if self.queries_logged: cursor = self.make_debug_cursor(self._cursor()) else: cursor = self.make_cursor(self._cursor()) return cur...
[ "def", "cursor", "(", "self", ")", ":", "self", ".", "validate_thread_sharing", "(", ")", "if", "self", ".", "queries_logged", ":", "cursor", "=", "self", ".", "make_debug_cursor", "(", "self", ".", "_cursor", "(", ")", ")", "else", ":", "cursor", "=", ...
[ 165, 4 ]
[ 174, 21 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.commit
(self)
Commits a transaction and resets the dirty flag.
Commits a transaction and resets the dirty flag.
def commit(self): """ Commits a transaction and resets the dirty flag. """ self.validate_thread_sharing() self.validate_no_atomic_block() self._commit() # A successful commit means that the database connection works. self.errors_occurred = False
[ "def", "commit", "(", "self", ")", ":", "self", ".", "validate_thread_sharing", "(", ")", "self", ".", "validate_no_atomic_block", "(", ")", "self", ".", "_commit", "(", ")", "# A successful commit means that the database connection works.", "self", ".", "errors_occur...
[ 176, 4 ]
[ 184, 36 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.rollback
(self)
Rolls back a transaction and resets the dirty flag.
Rolls back a transaction and resets the dirty flag.
def rollback(self): """ Rolls back a transaction and resets the dirty flag. """ self.validate_thread_sharing() self.validate_no_atomic_block() self._rollback() # A successful rollback means that the database connection works. self.errors_occurred = False
[ "def", "rollback", "(", "self", ")", ":", "self", ".", "validate_thread_sharing", "(", ")", "self", ".", "validate_no_atomic_block", "(", ")", "self", ".", "_rollback", "(", ")", "# A successful rollback means that the database connection works.", "self", ".", "errors...
[ 186, 4 ]
[ 194, 36 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.close
(self)
Closes the connection to the database.
Closes the connection to the database.
def close(self): """ Closes the connection to the database. """ self.validate_thread_sharing() # Don't call validate_no_atomic_block() to avoid making it difficult # to get rid of a connection in an invalid state. The next connect() # will reset the transaction st...
[ "def", "close", "(", "self", ")", ":", "self", ".", "validate_thread_sharing", "(", ")", "# Don't call validate_no_atomic_block() to avoid making it difficult", "# to get rid of a connection in an invalid state. The next connect()", "# will reset the transaction state anyway.", "if", "...
[ 196, 4 ]
[ 213, 38 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.savepoint
(self)
Creates a savepoint inside the current transaction. Returns an identifier for the savepoint that will be used for the subsequent rollback or commit. Does nothing if savepoints are not supported.
Creates a savepoint inside the current transaction. Returns an identifier for the savepoint that will be used for the subsequent rollback or commit. Does nothing if savepoints are not supported.
def savepoint(self): """ Creates a savepoint inside the current transaction. Returns an identifier for the savepoint that will be used for the subsequent rollback or commit. Does nothing if savepoints are not supported. """ if not self._savepoint_allowed(): re...
[ "def", "savepoint", "(", "self", ")", ":", "if", "not", "self", ".", "_savepoint_allowed", "(", ")", ":", "return", "thread_ident", "=", "thread", ".", "get_ident", "(", ")", "tid", "=", "str", "(", "thread_ident", ")", ".", "replace", "(", "'-'", ",",...
[ 235, 4 ]
[ 253, 18 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.savepoint_rollback
(self, sid)
Rolls back to a savepoint. Does nothing if savepoints are not supported.
Rolls back to a savepoint. Does nothing if savepoints are not supported.
def savepoint_rollback(self, sid): """ Rolls back to a savepoint. Does nothing if savepoints are not supported. """ if not self._savepoint_allowed(): return self.validate_thread_sharing() self._savepoint_rollback(sid)
[ "def", "savepoint_rollback", "(", "self", ",", "sid", ")", ":", "if", "not", "self", ".", "_savepoint_allowed", "(", ")", ":", "return", "self", ".", "validate_thread_sharing", "(", ")", "self", ".", "_savepoint_rollback", "(", "sid", ")" ]
[ 255, 4 ]
[ 263, 37 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.savepoint_commit
(self, sid)
Releases a savepoint. Does nothing if savepoints are not supported.
Releases a savepoint. Does nothing if savepoints are not supported.
def savepoint_commit(self, sid): """ Releases a savepoint. Does nothing if savepoints are not supported. """ if not self._savepoint_allowed(): return self.validate_thread_sharing() self._savepoint_commit(sid)
[ "def", "savepoint_commit", "(", "self", ",", "sid", ")", ":", "if", "not", "self", ".", "_savepoint_allowed", "(", ")", ":", "return", "self", ".", "validate_thread_sharing", "(", ")", "self", ".", "_savepoint_commit", "(", "sid", ")" ]
[ 265, 4 ]
[ 273, 35 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.clean_savepoints
(self)
Resets the counter used to generate unique savepoint ids in this thread.
Resets the counter used to generate unique savepoint ids in this thread.
def clean_savepoints(self): """ Resets the counter used to generate unique savepoint ids in this thread. """ self.savepoint_state = 0
[ "def", "clean_savepoints", "(", "self", ")", ":", "self", ".", "savepoint_state", "=", "0" ]
[ 275, 4 ]
[ 279, 32 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper._set_autocommit
(self, autocommit)
Backend-specific implementation to enable or disable autocommit.
Backend-specific implementation to enable or disable autocommit.
def _set_autocommit(self, autocommit): """ Backend-specific implementation to enable or disable autocommit. """ raise NotImplementedError('subclasses of BaseDatabaseWrapper may require a _set_autocommit() method')
[ "def", "_set_autocommit", "(", "self", ",", "autocommit", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseDatabaseWrapper may require a _set_autocommit() method'", ")" ]
[ 283, 4 ]
[ 287, 109 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.get_autocommit
(self)
Check the autocommit state.
Check the autocommit state.
def get_autocommit(self): """ Check the autocommit state. """ self.ensure_connection() return self.autocommit
[ "def", "get_autocommit", "(", "self", ")", ":", "self", ".", "ensure_connection", "(", ")", "return", "self", ".", "autocommit" ]
[ 291, 4 ]
[ 296, 30 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.set_autocommit
(self, autocommit)
Enable or disable autocommit.
Enable or disable autocommit.
def set_autocommit(self, autocommit): """ Enable or disable autocommit. """ self.validate_no_atomic_block() self.ensure_connection() self._set_autocommit(autocommit) self.autocommit = autocommit
[ "def", "set_autocommit", "(", "self", ",", "autocommit", ")", ":", "self", ".", "validate_no_atomic_block", "(", ")", "self", ".", "ensure_connection", "(", ")", "self", ".", "_set_autocommit", "(", "autocommit", ")", "self", ".", "autocommit", "=", "autocommi...
[ 298, 4 ]
[ 305, 36 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.get_rollback
(self)
Get the "needs rollback" flag -- for *advanced use* only.
Get the "needs rollback" flag -- for *advanced use* only.
def get_rollback(self): """ Get the "needs rollback" flag -- for *advanced use* only. """ if not self.in_atomic_block: raise TransactionManagementError( "The rollback flag doesn't work outside of an 'atomic' block.") return self.needs_rollback
[ "def", "get_rollback", "(", "self", ")", ":", "if", "not", "self", ".", "in_atomic_block", ":", "raise", "TransactionManagementError", "(", "\"The rollback flag doesn't work outside of an 'atomic' block.\"", ")", "return", "self", ".", "needs_rollback" ]
[ 307, 4 ]
[ 314, 34 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.set_rollback
(self, rollback)
Set or unset the "needs rollback" flag -- for *advanced use* only.
Set or unset the "needs rollback" flag -- for *advanced use* only.
def set_rollback(self, rollback): """ Set or unset the "needs rollback" flag -- for *advanced use* only. """ if not self.in_atomic_block: raise TransactionManagementError( "The rollback flag doesn't work outside of an 'atomic' block.") self.needs_rollb...
[ "def", "set_rollback", "(", "self", ",", "rollback", ")", ":", "if", "not", "self", ".", "in_atomic_block", ":", "raise", "TransactionManagementError", "(", "\"The rollback flag doesn't work outside of an 'atomic' block.\"", ")", "self", ".", "needs_rollback", "=", "rol...
[ 316, 4 ]
[ 323, 38 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.validate_no_atomic_block
(self)
Raise an error if an atomic block is active.
Raise an error if an atomic block is active.
def validate_no_atomic_block(self): """ Raise an error if an atomic block is active. """ if self.in_atomic_block: raise TransactionManagementError( "This is forbidden when an 'atomic' block is active.")
[ "def", "validate_no_atomic_block", "(", "self", ")", ":", "if", "self", ".", "in_atomic_block", ":", "raise", "TransactionManagementError", "(", "\"This is forbidden when an 'atomic' block is active.\"", ")" ]
[ 325, 4 ]
[ 331, 70 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.constraint_checks_disabled
(self)
Context manager that disables foreign key constraint checking.
Context manager that disables foreign key constraint checking.
def constraint_checks_disabled(self): """ Context manager that disables foreign key constraint checking. """ disabled = self.disable_constraint_checking() try: yield finally: if disabled: self.enable_constraint_checking()
[ "def", "constraint_checks_disabled", "(", "self", ")", ":", "disabled", "=", "self", ".", "disable_constraint_checking", "(", ")", "try", ":", "yield", "finally", ":", "if", "disabled", ":", "self", ".", "enable_constraint_checking", "(", ")" ]
[ 342, 4 ]
[ 351, 49 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.disable_constraint_checking
(self)
Backends can implement as needed to temporarily disable foreign key constraint checking. Should return True if the constraints were disabled and will need to be reenabled.
Backends can implement as needed to temporarily disable foreign key constraint checking. Should return True if the constraints were disabled and will need to be reenabled.
def disable_constraint_checking(self): """ Backends can implement as needed to temporarily disable foreign key constraint checking. Should return True if the constraints were disabled and will need to be reenabled. """ return False
[ "def", "disable_constraint_checking", "(", "self", ")", ":", "return", "False" ]
[ 353, 4 ]
[ 359, 20 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.enable_constraint_checking
(self)
Backends can implement as needed to re-enable foreign key constraint checking.
Backends can implement as needed to re-enable foreign key constraint checking.
def enable_constraint_checking(self): """ Backends can implement as needed to re-enable foreign key constraint checking. """ pass
[ "def", "enable_constraint_checking", "(", "self", ")", ":", "pass" ]
[ 361, 4 ]
[ 366, 12 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.check_constraints
(self, table_names=None)
Backends can override this method if they can apply constraint checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE"). Should raise an IntegrityError if any invalid foreign key references are encountered.
Backends can override this method if they can apply constraint checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE"). Should raise an IntegrityError if any invalid foreign key references are encountered.
def check_constraints(self, table_names=None): """ Backends can override this method if they can apply constraint checking (e.g. via "SET CONSTRAINTS ALL IMMEDIATE"). Should raise an IntegrityError if any invalid foreign key references are encountered. """ pass
[ "def", "check_constraints", "(", "self", ",", "table_names", "=", "None", ")", ":", "pass" ]
[ 368, 4 ]
[ 374, 12 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.is_usable
(self)
Tests if the database connection is usable. This function may assume that self.connection is not None. Actual implementations should take care not to raise exceptions as that may prevent Django from recycling unusable connections.
Tests if the database connection is usable.
def is_usable(self): """ Tests if the database connection is usable. This function may assume that self.connection is not None. Actual implementations should take care not to raise exceptions as that may prevent Django from recycling unusable connections. """ ra...
[ "def", "is_usable", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "\"subclasses of BaseDatabaseWrapper may require an is_usable() method\"", ")" ]
[ 378, 4 ]
[ 388, 82 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.close_if_unusable_or_obsolete
(self)
Closes the current connection if unrecoverable errors have occurred, or if it outlived its maximum age.
Closes the current connection if unrecoverable errors have occurred, or if it outlived its maximum age.
def close_if_unusable_or_obsolete(self): """ Closes the current connection if unrecoverable errors have occurred, or if it outlived its maximum age. """ if self.connection is not None: # If the application didn't restore the original autocommit setting, # ...
[ "def", "close_if_unusable_or_obsolete", "(", "self", ")", ":", "if", "self", ".", "connection", "is", "not", "None", ":", "# If the application didn't restore the original autocommit setting,", "# don't take chances, drop the connection.", "if", "self", ".", "get_autocommit", ...
[ 390, 4 ]
[ 413, 22 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.validate_thread_sharing
(self)
Validates that the connection isn't accessed by another thread than the one which originally created it, unless the connection was explicitly authorized to be shared between threads (via the `allow_thread_sharing` property). Raises an exception if the validation fails.
Validates that the connection isn't accessed by another thread than the one which originally created it, unless the connection was explicitly authorized to be shared between threads (via the `allow_thread_sharing` property). Raises an exception if the validation fails.
def validate_thread_sharing(self): """ Validates that the connection isn't accessed by another thread than the one which originally created it, unless the connection was explicitly authorized to be shared between threads (via the `allow_thread_sharing` property). Raises an except...
[ "def", "validate_thread_sharing", "(", "self", ")", ":", "if", "not", "(", "self", ".", "allow_thread_sharing", "or", "self", ".", "_thread_ident", "==", "thread", ".", "get_ident", "(", ")", ")", ":", "raise", "DatabaseError", "(", "\"DatabaseWrapper objects cr...
[ 417, 4 ]
[ 430, 71 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.wrap_database_errors
(self)
Context manager and decorator that re-throws backend-specific database exceptions using Django's common wrappers.
Context manager and decorator that re-throws backend-specific database exceptions using Django's common wrappers.
def wrap_database_errors(self): """ Context manager and decorator that re-throws backend-specific database exceptions using Django's common wrappers. """ return DatabaseErrorWrapper(self)
[ "def", "wrap_database_errors", "(", "self", ")", ":", "return", "DatabaseErrorWrapper", "(", "self", ")" ]
[ 435, 4 ]
[ 440, 41 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.make_debug_cursor
(self, cursor)
Creates a cursor that logs all queries in self.queries_log.
Creates a cursor that logs all queries in self.queries_log.
def make_debug_cursor(self, cursor): """ Creates a cursor that logs all queries in self.queries_log. """ return utils.CursorDebugWrapper(cursor, self)
[ "def", "make_debug_cursor", "(", "self", ",", "cursor", ")", ":", "return", "utils", ".", "CursorDebugWrapper", "(", "cursor", ",", "self", ")" ]
[ 442, 4 ]
[ 446, 53 ]
python
en
['en', 'error', 'th']
False
BaseDatabaseWrapper.make_cursor
(self, cursor)
Creates a cursor without debug logging.
Creates a cursor without debug logging.
def make_cursor(self, cursor): """ Creates a cursor without debug logging. """ return utils.CursorWrapper(cursor, self)
[ "def", "make_cursor", "(", "self", ",", "cursor", ")", ":", "return", "utils", ".", "CursorWrapper", "(", "cursor", ",", "self", ")" ]
[ 448, 4 ]
[ 452, 48 ]
python
en
['en', 'error', 'th']
False