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
LongNameTest.test_sequence_name_length_limits_m2m
(self)
Test an m2m save of a model with a long name and a long m2m field name doesn't error as on Django >=1.2 this now uses object saves. Ref #8901
Test an m2m save of a model with a long name and a long m2m field name doesn't error as on Django >=1.2 this now uses object saves. Ref #8901
def test_sequence_name_length_limits_m2m(self): """Test an m2m save of a model with a long name and a long m2m field name doesn't error as on Django >=1.2 this now uses object saves. Ref #8901""" obj = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create() rel_obj = ...
[ "def", "test_sequence_name_length_limits_m2m", "(", "self", ")", ":", "obj", "=", "models", ".", "VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ", ".", "objects", ".", "create", "(", ")", "rel_obj", "=", "models", ".", "Person", ".", "objects", ".", "cr...
[ 349, 4 ]
[ 353, 88 ]
python
en
['en', 'en', 'en']
True
LongNameTest.test_sequence_name_length_limits_flush
(self)
Test that sequence resetting as part of a flush with model with long name and long pk name doesn't error. Ref #8901
Test that sequence resetting as part of a flush with model with long name and long pk name doesn't error. Ref #8901
def test_sequence_name_length_limits_flush(self): """Test that sequence resetting as part of a flush with model with long name and long pk name doesn't error. Ref #8901""" # A full flush is expensive to the full test, so we dig into the # internals to generate the likely offending SQL and run it...
[ "def", "test_sequence_name_length_limits_flush", "(", "self", ")", ":", "# A full flush is expensive to the full test, so we dig into the", "# internals to generate the likely offending SQL and run it manually", "# Some convenience aliases", "VLM", "=", "models", ".", "VeryLongModelNameZZZ...
[ 355, 4 ]
[ 375, 37 ]
python
en
['en', 'en', 'en']
True
SequenceResetTest.test_generic_relation
(self)
Sequence names are correct when resetting generic relations (Ref #13941)
Sequence names are correct when resetting generic relations (Ref #13941)
def test_generic_relation(self): "Sequence names are correct when resetting generic relations (Ref #13941)" # Create an object with a manually specified PK models.Post.objects.create(id=10, name='1st post', text='hello world') # Reset the sequences for the database cursor = conn...
[ "def", "test_generic_relation", "(", "self", ")", ":", "# Create an object with a manually specified PK", "models", ".", "Post", ".", "objects", ".", "create", "(", "id", "=", "10", ",", "name", "=", "'1st post'", ",", "text", "=", "'hello world'", ")", "# Reset...
[ 380, 4 ]
[ 394, 36 ]
python
en
['en', 'en', 'en']
True
BackendTestCase.test_database_operations_init
(self)
Test that DatabaseOperations initialization doesn't query the database. See #17656.
Test that DatabaseOperations initialization doesn't query the database. See #17656.
def test_database_operations_init(self): """ Test that DatabaseOperations initialization doesn't query the database. See #17656. """ with self.assertNumQueries(0): connection.ops.__class__(connection)
[ "def", "test_database_operations_init", "(", "self", ")", ":", "with", "self", ".", "assertNumQueries", "(", "0", ")", ":", "connection", ".", "ops", ".", "__class__", "(", "connection", ")" ]
[ 573, 4 ]
[ 579, 48 ]
python
en
['en', 'error', 'th']
False
BackendTestCase.test_duplicate_table_error
(self)
Test that creating an existing table returns a DatabaseError
Test that creating an existing table returns a DatabaseError
def test_duplicate_table_error(self): """ Test that creating an existing table returns a DatabaseError """ cursor = connection.cursor() query = 'CREATE TABLE %s (id INTEGER);' % models.Article._meta.db_table with self.assertRaises(DatabaseError): cursor.execute(query)
[ "def", "test_duplicate_table_error", "(", "self", ")", ":", "cursor", "=", "connection", ".", "cursor", "(", ")", "query", "=", "'CREATE TABLE %s (id INTEGER);'", "%", "models", ".", "Article", ".", "_meta", ".", "db_table", "with", "self", ".", "assertRaises", ...
[ 586, 4 ]
[ 591, 33 ]
python
en
['en', 'en', 'en']
True
BackendTestCase.test_cursor_contextmanager
(self)
Test that cursors can be used as a context manager
Test that cursors can be used as a context manager
def test_cursor_contextmanager(self): """ Test that cursors can be used as a context manager """ with connection.cursor() as cursor: self.assertIsInstance(cursor, CursorWrapper) # Both InterfaceError and ProgrammingError seem to be used when # accessing closed...
[ "def", "test_cursor_contextmanager", "(", "self", ")", ":", "with", "connection", ".", "cursor", "(", ")", "as", "cursor", ":", "self", ".", "assertIsInstance", "(", "cursor", ",", "CursorWrapper", ")", "# Both InterfaceError and ProgrammingError seem to be used when", ...
[ 593, 4 ]
[ 604, 79 ]
python
en
['en', 'error', 'th']
False
BackendTestCase.test_is_usable_after_database_disconnects
(self)
Test that is_usable() doesn't crash when the database disconnects. Regression for #21553.
Test that is_usable() doesn't crash when the database disconnects.
def test_is_usable_after_database_disconnects(self): """ Test that is_usable() doesn't crash when the database disconnects. Regression for #21553. """ # Open a connection to the database. with connection.cursor(): pass # Emulate a connection close by ...
[ "def", "test_is_usable_after_database_disconnects", "(", "self", ")", ":", "# Open a connection to the database.", "with", "connection", ".", "cursor", "(", ")", ":", "pass", "# Emulate a connection close by the database.", "connection", ".", "_close", "(", ")", "# Even the...
[ 618, 4 ]
[ 638, 20 ]
python
en
['en', 'error', 'th']
False
BackendTestCase.test_queries
(self)
Test the documented API of connection.queries.
Test the documented API of connection.queries.
def test_queries(self): """ Test the documented API of connection.queries. """ reset_queries() with connection.cursor() as cursor: cursor.execute("SELECT 1" + connection.features.bare_select_suffix) self.assertEqual(1, len(connection.queries)) self.a...
[ "def", "test_queries", "(", "self", ")", ":", "reset_queries", "(", ")", "with", "connection", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", "\"SELECT 1\"", "+", "connection", ".", "features", ".", "bare_select_suffix", ")", ...
[ 641, 4 ]
[ 656, 52 ]
python
en
['en', 'error', 'th']
False
BackendTestCase.test_queries_limit
(self)
Test that the backend doesn't store an unlimited number of queries. Regression for #12581.
Test that the backend doesn't store an unlimited number of queries.
def test_queries_limit(self): """ Test that the backend doesn't store an unlimited number of queries. Regression for #12581. """ old_queries_limit = BaseDatabaseWrapper.queries_limit BaseDatabaseWrapper.queries_limit = 3 new_connections = ConnectionHandler(settin...
[ "def", "test_queries_limit", "(", "self", ")", ":", "old_queries_limit", "=", "BaseDatabaseWrapper", ".", "queries_limit", "BaseDatabaseWrapper", ".", "queries_limit", "=", "3", "new_connections", "=", "ConnectionHandler", "(", "settings", ".", "DATABASES", ")", "new_...
[ 661, 4 ]
[ 698, 34 ]
python
en
['en', 'error', 'th']
False
FkConstraintsTests.test_integrity_checks_on_creation
(self)
Try to create a model instance that violates a FK constraint. If it fails it should fail with IntegrityError.
Try to create a model instance that violates a FK constraint. If it fails it should fail with IntegrityError.
def test_integrity_checks_on_creation(self): """ Try to create a model instance that violates a FK constraint. If it fails it should fail with IntegrityError. """ a1 = models.Article(headline="This is a test", pub_date=datetime.datetime(2005, 7, 27), reporter_id=30) try: ...
[ "def", "test_integrity_checks_on_creation", "(", "self", ")", ":", "a1", "=", "models", ".", "Article", "(", "headline", "=", "\"This is a test\"", ",", "pub_date", "=", "datetime", ".", "datetime", "(", "2005", ",", "7", ",", "27", ")", ",", "reporter_id", ...
[ 716, 4 ]
[ 733, 50 ]
python
en
['en', 'error', 'th']
False
FkConstraintsTests.test_integrity_checks_on_update
(self)
Try to update a model instance introducing a FK constraint violation. If it fails it should fail with IntegrityError.
Try to update a model instance introducing a FK constraint violation. If it fails it should fail with IntegrityError.
def test_integrity_checks_on_update(self): """ Try to update a model instance introducing a FK constraint violation. If it fails it should fail with IntegrityError. """ # Create an Article. models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(...
[ "def", "test_integrity_checks_on_update", "(", "self", ")", ":", "# Create an Article.", "models", ".", "Article", ".", "objects", ".", "create", "(", "headline", "=", "\"Test article\"", ",", "pub_date", "=", "datetime", ".", "datetime", "(", "2010", ",", "9", ...
[ 735, 4 ]
[ 761, 50 ]
python
en
['en', 'error', 'th']
False
FkConstraintsTests.test_disable_constraint_checks_manually
(self)
When constraint checks are disabled, should be able to write bad data without IntegrityErrors.
When constraint checks are disabled, should be able to write bad data without IntegrityErrors.
def test_disable_constraint_checks_manually(self): """ When constraint checks are disabled, should be able to write bad data without IntegrityErrors. """ with transaction.atomic(): # Create an Article. models.Article.objects.create(headline="Test article", pub_dat...
[ "def", "test_disable_constraint_checks_manually", "(", "self", ")", ":", "with", "transaction", ".", "atomic", "(", ")", ":", "# Create an Article.", "models", ".", "Article", ".", "objects", ".", "create", "(", "headline", "=", "\"Test article\"", ",", "pub_date"...
[ 763, 4 ]
[ 779, 42 ]
python
en
['en', 'error', 'th']
False
FkConstraintsTests.test_disable_constraint_checks_context_manager
(self)
When constraint checks are disabled (using context manager), should be able to write bad data without IntegrityErrors.
When constraint checks are disabled (using context manager), should be able to write bad data without IntegrityErrors.
def test_disable_constraint_checks_context_manager(self): """ When constraint checks are disabled (using context manager), should be able to write bad data without IntegrityErrors. """ with transaction.atomic(): # Create an Article. models.Article.objects.create(h...
[ "def", "test_disable_constraint_checks_context_manager", "(", "self", ")", ":", "with", "transaction", ".", "atomic", "(", ")", ":", "# Create an Article.", "models", ".", "Article", ".", "objects", ".", "create", "(", "headline", "=", "\"Test article\"", ",", "pu...
[ 781, 4 ]
[ 796, 42 ]
python
en
['en', 'error', 'th']
False
FkConstraintsTests.test_check_constraints
(self)
Constraint checks should raise an IntegrityError when bad data is in the DB.
Constraint checks should raise an IntegrityError when bad data is in the DB.
def test_check_constraints(self): """ Constraint checks should raise an IntegrityError when bad data is in the DB. """ with transaction.atomic(): # Create an Article. models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), re...
[ "def", "test_check_constraints", "(", "self", ")", ":", "with", "transaction", ".", "atomic", "(", ")", ":", "# Create an Article.", "models", ".", "Article", ".", "objects", ".", "create", "(", "headline", "=", "\"Test article\"", ",", "pub_date", "=", "datet...
[ 798, 4 ]
[ 812, 42 ]
python
en
['en', 'error', 'th']
False
ThreadTests.test_default_connection_thread_local
(self)
Ensure that the default connection (i.e. django.db.connection) is different for each thread. Refs #17258.
Ensure that the default connection (i.e. django.db.connection) is different for each thread. Refs #17258.
def test_default_connection_thread_local(self): """ Ensure that the default connection (i.e. django.db.connection) is different for each thread. Refs #17258. """ # Map connections by id because connections with identical aliases # have the same hash. conne...
[ "def", "test_default_connection_thread_local", "(", "self", ")", ":", "# Map connections by id because connections with identical aliases", "# have the same hash.", "connections_dict", "=", "{", "}", "connection", ".", "cursor", "(", ")", "connections_dict", "[", "id", "(", ...
[ 817, 4 ]
[ 852, 28 ]
python
en
['en', 'error', 'th']
False
ThreadTests.test_connections_thread_local
(self)
Ensure that the connections are different for each thread. Refs #17258.
Ensure that the connections are different for each thread. Refs #17258.
def test_connections_thread_local(self): """ Ensure that the connections are different for each thread. Refs #17258. """ # Map connections by id because connections with identical aliases # have the same hash. connections_dict = {} for conn in connections....
[ "def", "test_connections_thread_local", "(", "self", ")", ":", "# Map connections by id because connections with identical aliases", "# have the same hash.", "connections_dict", "=", "{", "}", "for", "conn", "in", "connections", ".", "all", "(", ")", ":", "connections_dict"...
[ 854, 4 ]
[ 882, 28 ]
python
en
['en', 'error', 'th']
False
ThreadTests.test_pass_connection_between_threads
(self)
Ensure that a connection can be passed from one thread to the other. Refs #17258.
Ensure that a connection can be passed from one thread to the other. Refs #17258.
def test_pass_connection_between_threads(self): """ Ensure that a connection can be passed from one thread to the other. Refs #17258. """ models.Person.objects.create(first_name="John", last_name="Doe") def do_thread(): def runner(main_thread_connection): ...
[ "def", "test_pass_connection_between_threads", "(", "self", ")", ":", "models", ".", "Person", ".", "objects", ".", "create", "(", "first_name", "=", "\"John\"", ",", "last_name", "=", "\"Doe\"", ")", "def", "do_thread", "(", ")", ":", "def", "runner", "(", ...
[ 884, 4 ]
[ 921, 40 ]
python
en
['en', 'error', 'th']
False
ThreadTests.test_closing_non_shared_connections
(self)
Ensure that a connection that is not explicitly shareable cannot be closed by another thread. Refs #17258.
Ensure that a connection that is not explicitly shareable cannot be closed by another thread. Refs #17258.
def test_closing_non_shared_connections(self): """ Ensure that a connection that is not explicitly shareable cannot be closed by another thread. Refs #17258. """ # First, without explicitly enabling the connection for sharing. exceptions = set() def runne...
[ "def", "test_closing_non_shared_connections", "(", "self", ")", ":", "# First, without explicitly enabling the connection for sharing.", "exceptions", "=", "set", "(", ")", "def", "runner1", "(", ")", ":", "def", "runner2", "(", "other_thread_connection", ")", ":", "try...
[ 923, 4 ]
[ 965, 44 ]
python
en
['en', 'error', 'th']
False
BackendUtilTests.test_format_number
(self)
Test the format_number converter utility
Test the format_number converter utility
def test_format_number(self): """ Test the format_number converter utility """ def equal(value, max_d, places, result): self.assertEqual(format_number(Decimal(value), max_d, places), result) equal('0', 12, 3, '0.000') equal('0', 12, 8, ...
[ "def", "test_format_number", "(", "self", ")", ":", "def", "equal", "(", "value", ",", "max_d", ",", "places", ",", "result", ")", ":", "self", ".", "assertEqual", "(", "format_number", "(", "Decimal", "(", "value", ")", ",", "max_d", ",", "places", ")...
[ 1014, 4 ]
[ 1048, 18 ]
python
en
['en', 'error', 'th']
False
endswith_cr
(line)
Return True if line (a text or bytestring) ends with '\r'.
Return True if line (a text or bytestring) ends with '\r'.
def endswith_cr(line): """Return True if line (a text or bytestring) ends with '\r'.""" return line.endswith('\r' if isinstance(line, str) else b'\r')
[ "def", "endswith_cr", "(", "line", ")", ":", "return", "line", ".", "endswith", "(", "'\\r'", "if", "isinstance", "(", "line", ",", "str", ")", "else", "b'\\r'", ")" ]
[ 147, 0 ]
[ 149, 66 ]
python
en
['en', 'en', 'en']
True
endswith_lf
(line)
Return True if line (a text or bytestring) ends with '\n'.
Return True if line (a text or bytestring) ends with '\n'.
def endswith_lf(line): """Return True if line (a text or bytestring) ends with '\n'.""" return line.endswith('\n' if isinstance(line, str) else b'\n')
[ "def", "endswith_lf", "(", "line", ")", ":", "return", "line", ".", "endswith", "(", "'\\n'", "if", "isinstance", "(", "line", ",", "str", ")", "else", "b'\\n'", ")" ]
[ 152, 0 ]
[ 154, 66 ]
python
en
['en', 'en', 'en']
True
equals_lf
(line)
Return True if line (a text or bytestring) equals '\n'.
Return True if line (a text or bytestring) equals '\n'.
def equals_lf(line): """Return True if line (a text or bytestring) equals '\n'.""" return line == ('\n' if isinstance(line, str) else b'\n')
[ "def", "equals_lf", "(", "line", ")", ":", "return", "line", "==", "(", "'\\n'", "if", "isinstance", "(", "line", ",", "str", ")", "else", "b'\\n'", ")" ]
[ 157, 0 ]
[ 159, 61 ]
python
en
['en', 'en', 'en']
True
File.chunks
(self, chunk_size=None)
Read the file and yield chunks of ``chunk_size`` bytes (defaults to ``File.DEFAULT_CHUNK_SIZE``).
Read the file and yield chunks of ``chunk_size`` bytes (defaults to ``File.DEFAULT_CHUNK_SIZE``).
def chunks(self, chunk_size=None): """ Read the file and yield chunks of ``chunk_size`` bytes (defaults to ``File.DEFAULT_CHUNK_SIZE``). """ chunk_size = chunk_size or self.DEFAULT_CHUNK_SIZE try: self.seek(0) except (AttributeError, UnsupportedOperati...
[ "def", "chunks", "(", "self", ",", "chunk_size", "=", "None", ")", ":", "chunk_size", "=", "chunk_size", "or", "self", ".", "DEFAULT_CHUNK_SIZE", "try", ":", "self", ".", "seek", "(", "0", ")", "except", "(", "AttributeError", ",", "UnsupportedOperation", ...
[ 47, 4 ]
[ 62, 22 ]
python
en
['en', 'error', 'th']
False
File.multiple_chunks
(self, chunk_size=None)
Return ``True`` if you can expect multiple chunks. NB: If a particular file representation is in memory, subclasses should always return ``False`` -- there's no good reason to read from memory in chunks.
Return ``True`` if you can expect multiple chunks.
def multiple_chunks(self, chunk_size=None): """ Return ``True`` if you can expect multiple chunks. NB: If a particular file representation is in memory, subclasses should always return ``False`` -- there's no good reason to read from memory in chunks. """ return ...
[ "def", "multiple_chunks", "(", "self", ",", "chunk_size", "=", "None", ")", ":", "return", "self", ".", "size", ">", "(", "chunk_size", "or", "self", ".", "DEFAULT_CHUNK_SIZE", ")" ]
[ 64, 4 ]
[ 72, 66 ]
python
en
['en', 'error', 'th']
False
formset_factory
(form, formset=BaseFormSet, extra=1, can_order=False, can_delete=False, max_num=None, validate_max=False, min_num=None, validate_min=False)
Return a FormSet for the given form class.
Return a FormSet for the given form class.
def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False, can_delete=False, max_num=None, validate_max=False, min_num=None, validate_min=False): """Return a FormSet for the given form class.""" if min_num is None: min_num = DEFAULT_MIN_NUM if ma...
[ "def", "formset_factory", "(", "form", ",", "formset", "=", "BaseFormSet", ",", "extra", "=", "1", ",", "can_order", "=", "False", ",", "can_delete", "=", "False", ",", "max_num", "=", "None", ",", "validate_max", "=", "False", ",", "min_num", "=", "None...
[ 433, 0 ]
[ 456, 61 ]
python
en
['en', 'en', 'en']
True
all_valid
(formsets)
Validate every formset and return True if all are valid.
Validate every formset and return True if all are valid.
def all_valid(formsets): """Validate every formset and return True if all are valid.""" valid = True for formset in formsets: valid &= formset.is_valid() return valid
[ "def", "all_valid", "(", "formsets", ")", ":", "valid", "=", "True", "for", "formset", "in", "formsets", ":", "valid", "&=", "formset", ".", "is_valid", "(", ")", "return", "valid" ]
[ 459, 0 ]
[ 464, 16 ]
python
en
['en', 'en', 'en']
True
Left.__init__
(self, expression, length, **extra)
expression: the name of a field, or an expression returning a string length: the number of characters to return from the start of the string
expression: the name of a field, or an expression returning a string length: the number of characters to return from the start of the string
def __init__(self, expression, length, **extra): """ expression: the name of a field, or an expression returning a string length: the number of characters to return from the start of the string """ if not hasattr(length, 'resolve_expression'): if length < 1: ...
[ "def", "__init__", "(", "self", ",", "expression", ",", "length", ",", "*", "*", "extra", ")", ":", "if", "not", "hasattr", "(", "length", ",", "'resolve_expression'", ")", ":", "if", "length", "<", "1", ":", "raise", "ValueError", "(", "\"'length' must ...
[ 138, 4 ]
[ 146, 53 ]
python
en
['en', 'error', 'th']
False
Substr.__init__
(self, expression, pos, length=None, **extra)
expression: the name of a field, or an expression returning a string pos: an integer > 0, or an expression returning an integer length: an optional number of characters to return
expression: the name of a field, or an expression returning a string pos: an integer > 0, or an expression returning an integer length: an optional number of characters to return
def __init__(self, expression, pos, length=None, **extra): """ expression: the name of a field, or an expression returning a string pos: an integer > 0, or an expression returning an integer length: an optional number of characters to return """ if not hasattr(pos, 'resol...
[ "def", "__init__", "(", "self", ",", "expression", ",", "pos", ",", "length", "=", "None", ",", "*", "*", "extra", ")", ":", "if", "not", "hasattr", "(", "pos", ",", "'resolve_expression'", ")", ":", "if", "pos", "<", "1", ":", "raise", "ValueError",...
[ 306, 4 ]
[ 318, 47 ]
python
en
['en', 'error', 'th']
False
patch_cache_control
(response, **kwargs)
Patch the Cache-Control header by adding all keyword arguments to it. The transformation is as follows: * All keyword parameter names are turned to lowercase, and underscores are converted to hyphens. * If the value of a parameter is True (exactly True, not just a true value), only the par...
Patch the Cache-Control header by adding all keyword arguments to it. The transformation is as follows:
def patch_cache_control(response, **kwargs): """ Patch the Cache-Control header by adding all keyword arguments to it. The transformation is as follows: * All keyword parameter names are turned to lowercase, and underscores are converted to hyphens. * If the value of a parameter is True (exac...
[ "def", "patch_cache_control", "(", "response", ",", "*", "*", "kwargs", ")", ":", "def", "dictitem", "(", "s", ")", ":", "t", "=", "s", ".", "split", "(", "'='", ",", "1", ")", "if", "len", "(", "t", ")", ">", "1", ":", "return", "(", "t", "[...
[ 36, 0 ]
[ 82, 34 ]
python
en
['en', 'error', 'th']
False
get_max_age
(response)
Return the max-age from the response Cache-Control header as an integer, or None if it wasn't found or wasn't an integer.
Return the max-age from the response Cache-Control header as an integer, or None if it wasn't found or wasn't an integer.
def get_max_age(response): """ Return the max-age from the response Cache-Control header as an integer, or None if it wasn't found or wasn't an integer. """ if not response.has_header('Cache-Control'): return cc = dict(_to_tuple(el) for el in cc_delim_re.split(response['Cache-Control']))...
[ "def", "get_max_age", "(", "response", ")", ":", "if", "not", "response", ".", "has_header", "(", "'Cache-Control'", ")", ":", "return", "cc", "=", "dict", "(", "_to_tuple", "(", "el", ")", "for", "el", "in", "cc_delim_re", ".", "split", "(", "response",...
[ 85, 0 ]
[ 96, 12 ]
python
en
['en', 'error', 'th']
False
_if_match_passes
(target_etag, etags)
Test the If-Match comparison as defined in section 3.1 of RFC 7232.
Test the If-Match comparison as defined in section 3.1 of RFC 7232.
def _if_match_passes(target_etag, etags): """ Test the If-Match comparison as defined in section 3.1 of RFC 7232. """ if not target_etag: # If there isn't an ETag, then there can't be a match. return False elif etags == ['*']: # The existence of an ETag means that there is "a...
[ "def", "_if_match_passes", "(", "target_etag", ",", "etags", ")", ":", "if", "not", "target_etag", ":", "# If there isn't an ETag, then there can't be a match.", "return", "False", "elif", "etags", "==", "[", "'*'", "]", ":", "# The existence of an ETag means that there i...
[ 173, 0 ]
[ 191, 35 ]
python
en
['en', 'error', 'th']
False
_if_unmodified_since_passes
(last_modified, if_unmodified_since)
Test the If-Unmodified-Since comparison as defined in section 3.4 of RFC 7232.
Test the If-Unmodified-Since comparison as defined in section 3.4 of RFC 7232.
def _if_unmodified_since_passes(last_modified, if_unmodified_since): """ Test the If-Unmodified-Since comparison as defined in section 3.4 of RFC 7232. """ return last_modified and last_modified <= if_unmodified_since
[ "def", "_if_unmodified_since_passes", "(", "last_modified", ",", "if_unmodified_since", ")", ":", "return", "last_modified", "and", "last_modified", "<=", "if_unmodified_since" ]
[ 194, 0 ]
[ 199, 65 ]
python
en
['en', 'error', 'th']
False
_if_none_match_passes
(target_etag, etags)
Test the If-None-Match comparison as defined in section 3.2 of RFC 7232.
Test the If-None-Match comparison as defined in section 3.2 of RFC 7232.
def _if_none_match_passes(target_etag, etags): """ Test the If-None-Match comparison as defined in section 3.2 of RFC 7232. """ if not target_etag: # If there isn't an ETag, then there isn't a match. return True elif etags == ['*']: # The existence of an ETag means that there...
[ "def", "_if_none_match_passes", "(", "target_etag", ",", "etags", ")", ":", "if", "not", "target_etag", ":", "# If there isn't an ETag, then there isn't a match.", "return", "True", "elif", "etags", "==", "[", "'*'", "]", ":", "# The existence of an ETag means that there ...
[ 202, 0 ]
[ 218, 39 ]
python
en
['en', 'error', 'th']
False
_if_modified_since_passes
(last_modified, if_modified_since)
Test the If-Modified-Since comparison as defined in section 3.3 of RFC 7232.
Test the If-Modified-Since comparison as defined in section 3.3 of RFC 7232.
def _if_modified_since_passes(last_modified, if_modified_since): """ Test the If-Modified-Since comparison as defined in section 3.3 of RFC 7232. """ return not last_modified or last_modified > if_modified_since
[ "def", "_if_modified_since_passes", "(", "last_modified", ",", "if_modified_since", ")", ":", "return", "not", "last_modified", "or", "last_modified", ">", "if_modified_since" ]
[ 221, 0 ]
[ 225, 65 ]
python
en
['en', 'error', 'th']
False
patch_response_headers
(response, cache_timeout=None)
Add HTTP caching headers to the given HttpResponse: Expires and Cache-Control. Each header is only added if it isn't already set. cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDS setting is used by default.
Add HTTP caching headers to the given HttpResponse: Expires and Cache-Control.
def patch_response_headers(response, cache_timeout=None): """ Add HTTP caching headers to the given HttpResponse: Expires and Cache-Control. Each header is only added if it isn't already set. cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDS setting is used by default. """ if c...
[ "def", "patch_response_headers", "(", "response", ",", "cache_timeout", "=", "None", ")", ":", "if", "cache_timeout", "is", "None", ":", "cache_timeout", "=", "settings", ".", "CACHE_MIDDLEWARE_SECONDS", "if", "cache_timeout", "<", "0", ":", "cache_timeout", "=", ...
[ 228, 0 ]
[ 244, 56 ]
python
en
['en', 'error', 'th']
False
add_never_cache_headers
(response)
Add headers to a response to indicate that a page should never be cached.
Add headers to a response to indicate that a page should never be cached.
def add_never_cache_headers(response): """ Add headers to a response to indicate that a page should never be cached. """ patch_response_headers(response, cache_timeout=-1) patch_cache_control(response, no_cache=True, no_store=True, must_revalidate=True, private=True)
[ "def", "add_never_cache_headers", "(", "response", ")", ":", "patch_response_headers", "(", "response", ",", "cache_timeout", "=", "-", "1", ")", "patch_cache_control", "(", "response", ",", "no_cache", "=", "True", ",", "no_store", "=", "True", ",", "must_reval...
[ 247, 0 ]
[ 252, 99 ]
python
en
['en', 'error', 'th']
False
patch_vary_headers
(response, newheaders)
Add (or update) the "Vary" header in the given HttpResponse object. newheaders is a list of header names that should be in "Vary". If headers contains an asterisk, then "Vary" header will consist of a single asterisk '*'. Otherwise, existing headers in "Vary" aren't removed.
Add (or update) the "Vary" header in the given HttpResponse object. newheaders is a list of header names that should be in "Vary". If headers contains an asterisk, then "Vary" header will consist of a single asterisk '*'. Otherwise, existing headers in "Vary" aren't removed.
def patch_vary_headers(response, newheaders): """ Add (or update) the "Vary" header in the given HttpResponse object. newheaders is a list of header names that should be in "Vary". If headers contains an asterisk, then "Vary" header will consist of a single asterisk '*'. Otherwise, existing headers ...
[ "def", "patch_vary_headers", "(", "response", ",", "newheaders", ")", ":", "# Note that we need to keep the original order intact, because cache", "# implementations may rely on the order of the Vary contents in, say,", "# computing an MD5 hash.", "if", "response", ".", "has_header", "...
[ 255, 0 ]
[ 277, 50 ]
python
en
['en', 'error', 'th']
False
has_vary_header
(response, header_query)
Check to see if the response has a given header name in its Vary header.
Check to see if the response has a given header name in its Vary header.
def has_vary_header(response, header_query): """ Check to see if the response has a given header name in its Vary header. """ if not response.has_header('Vary'): return False vary_headers = cc_delim_re.split(response['Vary']) existing_headers = {header.lower() for header in vary_headers}...
[ "def", "has_vary_header", "(", "response", ",", "header_query", ")", ":", "if", "not", "response", ".", "has_header", "(", "'Vary'", ")", ":", "return", "False", "vary_headers", "=", "cc_delim_re", ".", "split", "(", "response", "[", "'Vary'", "]", ")", "e...
[ 280, 0 ]
[ 288, 51 ]
python
en
['en', 'error', 'th']
False
_i18n_cache_key_suffix
(request, cache_key)
If necessary, add the current locale or time zone to the cache key.
If necessary, add the current locale or time zone to the cache key.
def _i18n_cache_key_suffix(request, cache_key): """If necessary, add the current locale or time zone to the cache key.""" if settings.USE_I18N or settings.USE_L10N: # first check if LocaleMiddleware or another middleware added # LANGUAGE_CODE to request, then fall back to the active language ...
[ "def", "_i18n_cache_key_suffix", "(", "request", ",", "cache_key", ")", ":", "if", "settings", ".", "USE_I18N", "or", "settings", ".", "USE_L10N", ":", "# first check if LocaleMiddleware or another middleware added", "# LANGUAGE_CODE to request, then fall back to the active langu...
[ 291, 0 ]
[ 300, 20 ]
python
en
['en', 'en', 'en']
True
_generate_cache_key
(request, method, headerlist, key_prefix)
Return a cache key from the headers given in the header list.
Return a cache key from the headers given in the header list.
def _generate_cache_key(request, method, headerlist, key_prefix): """Return a cache key from the headers given in the header list.""" ctx = hashlib.md5() for header in headerlist: value = request.META.get(header) if value is not None: ctx.update(value.encode()) url = hashlib....
[ "def", "_generate_cache_key", "(", "request", ",", "method", ",", "headerlist", ",", "key_prefix", ")", ":", "ctx", "=", "hashlib", ".", "md5", "(", ")", "for", "header", "in", "headerlist", ":", "value", "=", "request", ".", "META", ".", "get", "(", "...
[ 303, 0 ]
[ 313, 53 ]
python
en
['en', 'en', 'en']
True
_generate_cache_header_key
(key_prefix, request)
Return a cache key for the header cache.
Return a cache key for the header cache.
def _generate_cache_header_key(key_prefix, request): """Return a cache key for the header cache.""" url = hashlib.md5(iri_to_uri(request.build_absolute_uri()).encode('ascii')) cache_key = 'views.decorators.cache.cache_header.%s.%s' % ( key_prefix, url.hexdigest()) return _i18n_cache_key_suffix(r...
[ "def", "_generate_cache_header_key", "(", "key_prefix", ",", "request", ")", ":", "url", "=", "hashlib", ".", "md5", "(", "iri_to_uri", "(", "request", ".", "build_absolute_uri", "(", ")", ")", ".", "encode", "(", "'ascii'", ")", ")", "cache_key", "=", "'v...
[ 316, 0 ]
[ 321, 53 ]
python
en
['en', 'en', 'en']
True
get_cache_key
(request, key_prefix=None, method='GET', cache=None)
Return a cache key based on the request URL and query. It can be used in the request phase because it pulls the list of headers to take into account from the global URL registry and uses those to build a cache key to check against. If there isn't a headerlist stored, return None, indicating that t...
Return a cache key based on the request URL and query. It can be used in the request phase because it pulls the list of headers to take into account from the global URL registry and uses those to build a cache key to check against.
def get_cache_key(request, key_prefix=None, method='GET', cache=None): """ Return a cache key based on the request URL and query. It can be used in the request phase because it pulls the list of headers to take into account from the global URL registry and uses those to build a cache key to check ag...
[ "def", "get_cache_key", "(", "request", ",", "key_prefix", "=", "None", ",", "method", "=", "'GET'", ",", "cache", "=", "None", ")", ":", "if", "key_prefix", "is", "None", ":", "key_prefix", "=", "settings", ".", "CACHE_MIDDLEWARE_KEY_PREFIX", "cache_key", "...
[ 324, 0 ]
[ 343, 19 ]
python
en
['en', 'error', 'th']
False
learn_cache_key
(request, response, cache_timeout=None, key_prefix=None, cache=None)
Learn what headers to take into account for some request URL from the response object. Store those headers in a global URL registry so that later access to that URL will know what headers to take into account without building the response object itself. The headers are named in the Vary header of t...
Learn what headers to take into account for some request URL from the response object. Store those headers in a global URL registry so that later access to that URL will know what headers to take into account without building the response object itself. The headers are named in the Vary header of t...
def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None): """ Learn what headers to take into account for some request URL from the response object. Store those headers in a global URL registry so that later access to that URL will know what headers to take into account ...
[ "def", "learn_cache_key", "(", "request", ",", "response", ",", "cache_timeout", "=", "None", ",", "key_prefix", "=", "None", ",", "cache", "=", "None", ")", ":", "if", "key_prefix", "is", "None", ":", "key_prefix", "=", "settings", ".", "CACHE_MIDDLEWARE_KE...
[ 346, 0 ]
[ 384, 75 ]
python
en
['en', 'error', 'th']
False
get_old_and_new_values
(change_type: str, message: Mapping[str, Any])
Parses the payload and finds previous and current value of change_type.
Parses the payload and finds previous and current value of change_type.
def get_old_and_new_values(change_type: str, message: Mapping[str, Any]) -> return_type: """ Parses the payload and finds previous and current value of change_type.""" old = message["change"]["diff"][change_type].get("from") new = message["change"]["diff"][change_type].get("to") return old, new
[ "def", "get_old_and_new_values", "(", "change_type", ":", "str", ",", "message", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "return_type", ":", "old", "=", "message", "[", "\"change\"", "]", "[", "\"diff\"", "]", "[", "change_type", "]", "."...
[ 158, 0 ]
[ 162, 19 ]
python
en
['en', 'en', 'en']
True
parse_comment
(message: Mapping[str, Any])
Parses the comment to issue, task or US.
Parses the comment to issue, task or US.
def parse_comment(message: Mapping[str, Any]) -> Dict[str, Any]: """ Parses the comment to issue, task or US. """ return { "event": "commented", "type": message["type"], "values": { "user": get_owner_name(message), "user_link": get_owner_link(message), ...
[ "def", "parse_comment", "(", "message", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "return", "{", "\"event\"", ":", "\"commented\"", ",", "\"type\"", ":", "message", "[", "\"type\"", "]", ",", "\...
[ 165, 0 ]
[ 175, 5 ]
python
en
['en', 'en', 'en']
True
parse_create_or_delete
(message: Mapping[str, Any])
Parses create or delete event.
Parses create or delete event.
def parse_create_or_delete(message: Mapping[str, Any]) -> Dict[str, Any]: """ Parses create or delete event. """ if message["type"] == "relateduserstory": return { "type": message["type"], "event": message["action"], "values": { "user": get_owner_name(...
[ "def", "parse_create_or_delete", "(", "message", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "if", "message", "[", "\"type\"", "]", "==", "\"relateduserstory\"", ":", "return", "{", "\"type\"", ":", ...
[ 178, 0 ]
[ 200, 5 ]
python
en
['es', 'la', 'en']
False
parse_change_event
(change_type: str, message: Mapping[str, Any])
Parses change event.
Parses change event.
def parse_change_event(change_type: str, message: Mapping[str, Any]) -> Optional[Dict[str, Any]]: """ Parses change event. """ evt: Dict[str, Any] = {} values: Dict[str, Any] = { "user": get_owner_name(message), "user_link": get_owner_link(message), "subject": get_subject(message), ...
[ "def", "parse_change_event", "(", "change_type", ":", "str", ",", "message", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "evt", ":", "Dict", "[", "str", ",", "Any", "]", ...
[ 203, 0 ]
[ 271, 14 ]
python
en
['es', 'fr', 'en']
False
parse_message
(message: Mapping[str, Any])
Parses the payload by delegating to specialized functions.
Parses the payload by delegating to specialized functions.
def parse_message(message: Mapping[str, Any]) -> List[Dict[str, Any]]: """ Parses the payload by delegating to specialized functions. """ events = [] if message["action"] in ["create", "delete"]: events.append(parse_create_or_delete(message)) elif message["action"] == "change": if messag...
[ "def", "parse_message", "(", "message", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "events", "=", "[", "]", "if", "message", "[", "\"action\"", "]", "in", "[", "\"create\"", ...
[ 286, 0 ]
[ 302, 17 ]
python
en
['en', 'en', 'en']
True
generate_content
(data: Mapping[str, Any])
Gets the template string and formats it with parsed data.
Gets the template string and formats it with parsed data.
def generate_content(data: Mapping[str, Any]) -> str: """ Gets the template string and formats it with parsed data. """ template = templates[data["type"]][data["event"]] content = template.format(**data["values"]) return content
[ "def", "generate_content", "(", "data", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "str", ":", "template", "=", "templates", "[", "data", "[", "\"type\"", "]", "]", "[", "data", "[", "\"event\"", "]", "]", "content", "=", "template", "."...
[ 305, 0 ]
[ 309, 18 ]
python
en
['en', 'en', 'en']
True
save_pdf
(path)
Saves a pdf of the current matplotlib figure. :param path: str, filepath to save to
Saves a pdf of the current matplotlib figure.
def save_pdf(path): """ Saves a pdf of the current matplotlib figure. :param path: str, filepath to save to """ pp = PdfPages(path) pp.savefig(pyplot.gcf()) pp.close()
[ "def", "save_pdf", "(", "path", ")", ":", "pp", "=", "PdfPages", "(", "path", ")", "pp", ".", "savefig", "(", "pyplot", ".", "gcf", "(", ")", ")", "pp", ".", "close", "(", ")" ]
[ 7, 0 ]
[ 16, 14 ]
python
en
['en', 'error', 'th']
False
TestSessionAuthenticationMiddleware.test_changed_password_invalidates_session
(self)
Tests that changing a user's password invalidates the session.
Tests that changing a user's password invalidates the session.
def test_changed_password_invalidates_session(self): """ Tests that changing a user's password invalidates the session. """ verification_middleware = SessionAuthenticationMiddleware() self.assertTrue(self.client.login( username=self.user.username, password...
[ "def", "test_changed_password_invalidates_session", "(", "self", ")", ":", "verification_middleware", "=", "SessionAuthenticationMiddleware", "(", ")", "self", ".", "assertTrue", "(", "self", ".", "client", ".", "login", "(", "username", "=", "self", ".", "user", ...
[ 13, 4 ]
[ 34, 52 ]
python
en
['en', 'error', 'th']
False
ServerHandler.write
(self, data)
write()' callable as specified by PEP 3333
write()' callable as specified by PEP 3333
def write(self, data): """'write()' callable as specified by PEP 3333""" assert isinstance(data, bytes), "write() argument must be bytestring" if not self.status: raise AssertionError("write() before start_response()") elif not self.headers_sent: # Before the f...
[ "def", "write", "(", "self", ",", "data", ")", ":", "assert", "isinstance", "(", "data", ",", "bytes", ")", ",", "\"write() argument must be bytestring\"", "if", "not", "self", ".", "status", ":", "raise", "AssertionError", "(", "\"write() before start_response()\...
[ 18, 4 ]
[ 37, 25 ]
python
en
['en', 'en', 'en']
True
init_worker
(counter: "multiprocessing.sharedctypes._Value")
This function runs only under parallel mode. It initializes the individual processes which are also called workers.
This function runs only under parallel mode. It initializes the individual processes which are also called workers.
def init_worker(counter: "multiprocessing.sharedctypes._Value") -> None: """ This function runs only under parallel mode. It initializes the individual processes which are also called workers. """ global _worker_id with counter.get_lock(): counter.value += 1 _worker_id = counter...
[ "def", "init_worker", "(", "counter", ":", "\"multiprocessing.sharedctypes._Value\"", ")", "->", "None", ":", "global", "_worker_id", "with", "counter", ".", "get_lock", "(", ")", ":", "counter", ".", "value", "+=", "1", "_worker_id", "=", "counter", ".", "val...
[ 208, 0 ]
[ 240, 56 ]
python
en
['en', 'error', 'th']
False
file_move_safe
(old_file_name, new_file_name, chunk_size=1024 * 64, allow_overwrite=False)
Move a file from one location to another in the safest way possible. First, try ``os.rename``, which is simple but will break across filesystems. If that fails, stream manually from one file to another in pure Python. If the destination file exists and ``allow_overwrite`` is ``False``, raise ``Fi...
Move a file from one location to another in the safest way possible.
def file_move_safe(old_file_name, new_file_name, chunk_size=1024 * 64, allow_overwrite=False): """ Move a file from one location to another in the safest way possible. First, try ``os.rename``, which is simple but will break across filesystems. If that fails, stream manually from one file to another in...
[ "def", "file_move_safe", "(", "old_file_name", ",", "new_file_name", ",", "chunk_size", "=", "1024", "*", "64", ",", "allow_overwrite", "=", "False", ")", ":", "# There's no reason to move if we don't have to.", "if", "_samefile", "(", "old_file_name", ",", "new_file_...
[ 29, 0 ]
[ 86, 17 ]
python
en
['en', 'error', 'th']
False
access_user_by_id
( user_profile: UserProfile, target_user_id: int, *, allow_deactivated: bool = False, allow_bots: bool = False, for_admin: bool, )
Master function for accessing another user by ID in API code; verifies the user ID is in the same realm, and if requested checks for administrative privileges, with flags for various special cases.
Master function for accessing another user by ID in API code; verifies the user ID is in the same realm, and if requested checks for administrative privileges, with flags for various special cases.
def access_user_by_id( user_profile: UserProfile, target_user_id: int, *, allow_deactivated: bool = False, allow_bots: bool = False, for_admin: bool, ) -> UserProfile: """Master function for accessing another user by ID in API code; verifies the user ID is in the same realm, and if reque...
[ "def", "access_user_by_id", "(", "user_profile", ":", "UserProfile", ",", "target_user_id", ":", "int", ",", "*", ",", "allow_deactivated", ":", "bool", "=", "False", ",", "allow_bots", ":", "bool", "=", "False", ",", "for_admin", ":", "bool", ",", ")", "-...
[ 242, 0 ]
[ 268, 17 ]
python
en
['en', 'en', 'en']
True
format_user_row
( realm: Realm, acting_user: Optional[UserProfile], row: Dict[str, Any], client_gravatar: bool, user_avatar_url_field_optional: bool, custom_profile_field_data: Optional[Dict[str, Any]] = None, )
Formats a user row returned by a database fetch using .values(*realm_user_dict_fields) into a dictionary representation of that user for API delivery to clients. The acting_user argument is used for permissions checks.
Formats a user row returned by a database fetch using .values(*realm_user_dict_fields) into a dictionary representation of that user for API delivery to clients. The acting_user argument is used for permissions checks.
def format_user_row( realm: Realm, acting_user: Optional[UserProfile], row: Dict[str, Any], client_gravatar: bool, user_avatar_url_field_optional: bool, custom_profile_field_data: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: """Formats a user row returned by a database fetch using ...
[ "def", "format_user_row", "(", "realm", ":", "Realm", ",", "acting_user", ":", "Optional", "[", "UserProfile", "]", ",", "row", ":", "Dict", "[", "str", ",", "Any", "]", ",", "client_gravatar", ":", "bool", ",", "user_avatar_url_field_optional", ":", "bool",...
[ 351, 0 ]
[ 428, 17 ]
python
en
['en', 'en', 'en']
True
get_raw_user_data
( realm: Realm, acting_user: Optional[UserProfile], *, target_user: Optional[UserProfile] = None, client_gravatar: bool, user_avatar_url_field_optional: bool, include_custom_profile_fields: bool = True, )
Fetches data about the target user(s) appropriate for sending to acting_user via the standard format for the Zulip API. If target_user is None, we fetch all users in the realm.
Fetches data about the target user(s) appropriate for sending to acting_user via the standard format for the Zulip API. If target_user is None, we fetch all users in the realm.
def get_raw_user_data( realm: Realm, acting_user: Optional[UserProfile], *, target_user: Optional[UserProfile] = None, client_gravatar: bool, user_avatar_url_field_optional: bool, include_custom_profile_fields: bool = True, ) -> Dict[int, Dict[str, str]]: """Fetches data about the target...
[ "def", "get_raw_user_data", "(", "realm", ":", "Realm", ",", "acting_user", ":", "Optional", "[", "UserProfile", "]", ",", "*", ",", "target_user", ":", "Optional", "[", "UserProfile", "]", "=", "None", ",", "client_gravatar", ":", "bool", ",", "user_avatar_...
[ 504, 0 ]
[ 548, 17 ]
python
en
['en', 'en', 'en']
True
import_source_code
(module_name: str, path: Path)
Dynamically create and load module from python source code. Args: module_name: name of new module to create. path: path to source code. Returns: Dynamically created module.
Dynamically create and load module from python source code.
def import_source_code(module_name: str, path: Path) -> ModuleType: """Dynamically create and load module from python source code. Args: module_name: name of new module to create. path: path to source code. Returns: Dynamically created module. """ spec = importlib.util.spe...
[ "def", "import_source_code", "(", "module_name", ":", "str", ",", "path", ":", "Path", ")", "->", "ModuleType", ":", "spec", "=", "importlib", ".", "util", ".", "spec_from_file_location", "(", "module_name", ",", "path", ")", "module", "=", "importlib", ".",...
[ 10, 0 ]
[ 25, 17 ]
python
en
['en', 'en', 'en']
True
import_stubber
()
Dynamically import stubber. We do this because `micropython-stubs` is not a python package, so we can't import from it as you would normally.
Dynamically import stubber.
def import_stubber() -> ModuleType: """Dynamically import stubber. We do this because `micropython-stubs` is not a python package, so we can't import from it as you would normally. """ vers_path = micropy.data.STUBBER / "src" / "version.py" src_path = micropy.data.STUBBER / "src" / "utils.py" ...
[ "def", "import_stubber", "(", ")", "->", "ModuleType", ":", "vers_path", "=", "micropy", ".", "data", ".", "STUBBER", "/", "\"src\"", "/", "\"version.py\"", "src_path", "=", "micropy", ".", "data", ".", "STUBBER", "/", "\"src\"", "/", "\"utils.py\"", "# stub...
[ 28, 0 ]
[ 40, 14 ]
python
en
['en', 'en', 'en']
True
generate_stub
(path, log_func=None)
Create Stub from local .py file. Args: path (str): Path to file log_func (func, optional): Callback function for logging. Defaults to None. Returns: tuple: Tuple of file path and generated stub path.
Create Stub from local .py file.
def generate_stub(path, log_func=None): """Create Stub from local .py file. Args: path (str): Path to file log_func (func, optional): Callback function for logging. Defaults to None. Returns: tuple: Tuple of file path and generated stub path. """ stubgen = impo...
[ "def", "generate_stub", "(", "path", ",", "log_func", "=", "None", ")", ":", "stubgen", "=", "import_stubber", "(", ")", "# Monkeypatch print to prevent or wrap output", "logfn", "=", "log_func", "or", "(", "lambda", "*", "a", ":", "None", ")", "stubgen", ".",...
[ 43, 0 ]
[ 70, 16 ]
python
en
['en', 'en', 'en']
True
_best_version
(fields)
Detect the best version depending on the fields used.
Detect the best version depending on the fields used.
def _best_version(fields): """Detect the best version depending on the fields used.""" def _has_marker(keys, markers): for marker in markers: if marker in keys: return True return False keys = [] for key, value in fields.items(): if value in ([], 'UNK...
[ "def", "_best_version", "(", "fields", ")", ":", "def", "_has_marker", "(", "keys", ",", "markers", ")", ":", "for", "marker", "in", "markers", ":", "if", "marker", "in", "keys", ":", "return", "True", "return", "False", "keys", "=", "[", "]", "for", ...
[ 125, 0 ]
[ 194, 16 ]
python
en
['en', 'en', 'en']
True
_get_name_and_version
(name, version, for_filename=False)
Return the distribution name with version. If for_filename is true, return a filename-escaped form.
Return the distribution name with version.
def _get_name_and_version(name, version, for_filename=False): """Return the distribution name with version. If for_filename is true, return a filename-escaped form.""" if for_filename: # For both name and version any runs of non-alphanumeric or '.' # characters are replaced with a single '-...
[ "def", "_get_name_and_version", "(", "name", ",", "version", ",", "for_filename", "=", "False", ")", ":", "if", "for_filename", ":", "# For both name and version any runs of non-alphanumeric or '.'", "# characters are replaced with a single '-'. Additionally any", "# spaces in the...
[ 248, 0 ]
[ 258, 36 ]
python
en
['en', 'en', 'en']
True
LegacyMetadata.get_fullname
(self, filesafe=False)
Return the distribution name with version. If filesafe is true, return a filename-escaped form.
Return the distribution name with version.
def get_fullname(self, filesafe=False): """Return the distribution name with version. If filesafe is true, return a filename-escaped form.""" return _get_name_and_version(self['Name'], self['Version'], filesafe)
[ "def", "get_fullname", "(", "self", ",", "filesafe", "=", "False", ")", ":", "return", "_get_name_and_version", "(", "self", "[", "'Name'", "]", ",", "self", "[", "'Version'", "]", ",", "filesafe", ")" ]
[ 340, 4 ]
[ 344, 77 ]
python
en
['en', 'en', 'en']
True
LegacyMetadata.is_field
(self, name)
return True if name is a valid metadata key
return True if name is a valid metadata key
def is_field(self, name): """return True if name is a valid metadata key""" name = self._convert_name(name) return name in _ALL_FIELDS
[ "def", "is_field", "(", "self", ",", "name", ")", ":", "name", "=", "self", ".", "_convert_name", "(", "name", ")", "return", "name", "in", "_ALL_FIELDS" ]
[ 346, 4 ]
[ 349, 34 ]
python
en
['en', 'et', 'en']
True
LegacyMetadata.read
(self, filepath)
Read the metadata values from a file path.
Read the metadata values from a file path.
def read(self, filepath): """Read the metadata values from a file path.""" fp = codecs.open(filepath, 'r', encoding='utf-8') try: self.read_file(fp) finally: fp.close()
[ "def", "read", "(", "self", ",", "filepath", ")", ":", "fp", "=", "codecs", ".", "open", "(", "filepath", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "try", ":", "self", ".", "read_file", "(", "fp", ")", "finally", ":", "fp", ".", "close", ...
[ 355, 4 ]
[ 361, 22 ]
python
en
['en', 'en', 'en']
True
LegacyMetadata.read_file
(self, fileob)
Read the metadata values from a file object.
Read the metadata values from a file object.
def read_file(self, fileob): """Read the metadata values from a file object.""" msg = message_from_file(fileob) self._fields['Metadata-Version'] = msg['metadata-version'] # When reading, get all the fields we can for field in _ALL_FIELDS: if field not in msg: ...
[ "def", "read_file", "(", "self", ",", "fileob", ")", ":", "msg", "=", "message_from_file", "(", "fileob", ")", "self", ".", "_fields", "[", "'Metadata-Version'", "]", "=", "msg", "[", "'metadata-version'", "]", "# When reading, get all the fields we can", "for", ...
[ 363, 4 ]
[ 382, 42 ]
python
en
['en', 'en', 'en']
True
LegacyMetadata.write
(self, filepath, skip_unknown=False)
Write the metadata fields to filepath.
Write the metadata fields to filepath.
def write(self, filepath, skip_unknown=False): """Write the metadata fields to filepath.""" fp = codecs.open(filepath, 'w', encoding='utf-8') try: self.write_file(fp, skip_unknown) finally: fp.close()
[ "def", "write", "(", "self", ",", "filepath", ",", "skip_unknown", "=", "False", ")", ":", "fp", "=", "codecs", ".", "open", "(", "filepath", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "try", ":", "self", ".", "write_file", "(", "fp", ",", "...
[ 386, 4 ]
[ 392, 22 ]
python
en
['en', 'el-Latn', 'en']
True
LegacyMetadata.write_file
(self, fileobject, skip_unknown=False)
Write the PKG-INFO format data to a file object.
Write the PKG-INFO format data to a file object.
def write_file(self, fileobject, skip_unknown=False): """Write the PKG-INFO format data to a file object.""" self.set_metadata_version() for field in _version2fieldlist(self['Metadata-Version']): values = self.get(field) if skip_unknown and values in ('UNKNOWN', [], ['UN...
[ "def", "write_file", "(", "self", ",", "fileobject", ",", "skip_unknown", "=", "False", ")", ":", "self", ".", "set_metadata_version", "(", ")", "for", "field", "in", "_version2fieldlist", "(", "self", "[", "'Metadata-Version'", "]", ")", ":", "values", "=",...
[ 394, 4 ]
[ 417, 59 ]
python
en
['en', 'en', 'en']
True
LegacyMetadata.update
(self, other=None, **kwargs)
Set metadata values from the given iterable `other` and kwargs. Behavior is like `dict.update`: If `other` has a ``keys`` method, they are looped over and ``self[key]`` is assigned ``other[key]``. Else, ``other`` is an iterable of ``(key, value)`` iterables. Keys that don't match a met...
Set metadata values from the given iterable `other` and kwargs.
def update(self, other=None, **kwargs): """Set metadata values from the given iterable `other` and kwargs. Behavior is like `dict.update`: If `other` has a ``keys`` method, they are looped over and ``self[key]`` is assigned ``other[key]``. Else, ``other`` is an iterable of ``(key, value...
[ "def", "update", "(", "self", ",", "other", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "_set", "(", "key", ",", "value", ")", ":", "if", "key", "in", "_ATTR2FIELD", "and", "value", ":", "self", ".", "set", "(", "self", ".", "_convert_...
[ 419, 4 ]
[ 445, 26 ]
python
en
['en', 'en', 'en']
True
LegacyMetadata.set
(self, name, value)
Control then set a metadata field.
Control then set a metadata field.
def set(self, name, value): """Control then set a metadata field.""" name = self._convert_name(name) if ((name in _ELEMENTSFIELD or name == 'Platform') and not isinstance(value, (list, tuple))): if isinstance(value, string_types): value = [v.strip() for v...
[ "def", "set", "(", "self", ",", "name", ",", "value", ")", ":", "name", "=", "self", ".", "_convert_name", "(", "name", ")", "if", "(", "(", "name", "in", "_ELEMENTSFIELD", "or", "name", "==", "'Platform'", ")", "and", "not", "isinstance", "(", "valu...
[ 447, 4 ]
[ 489, 34 ]
python
en
['en', 'lb', 'en']
True
LegacyMetadata.get
(self, name, default=_MISSING)
Get a metadata field.
Get a metadata field.
def get(self, name, default=_MISSING): """Get a metadata field.""" name = self._convert_name(name) if name not in self._fields: if default is _MISSING: default = self._default_value(name) return default if name in _UNICODEFIELDS: value ...
[ "def", "get", "(", "self", ",", "name", ",", "default", "=", "_MISSING", ")", ":", "name", "=", "self", ".", "_convert_name", "(", "name", ")", "if", "name", "not", "in", "self", ".", "_fields", ":", "if", "default", "is", "_MISSING", ":", "default",...
[ 491, 4 ]
[ 518, 33 ]
python
en
['ro', 'lb', 'en']
False
LegacyMetadata.check
(self, strict=False)
Check if the metadata is compliant. If strict is True then raise if no Name or Version are provided
Check if the metadata is compliant. If strict is True then raise if no Name or Version are provided
def check(self, strict=False): """Check if the metadata is compliant. If strict is True then raise if no Name or Version are provided""" self.set_metadata_version() # XXX should check the versions (if the file was loaded) missing, warnings = [], [] for attr in ('Name', ...
[ "def", "check", "(", "self", ",", "strict", "=", "False", ")", ":", "self", ".", "set_metadata_version", "(", ")", "# XXX should check the versions (if the file was loaded)", "missing", ",", "warnings", "=", "[", "]", ",", "[", "]", "for", "attr", "in", "(", ...
[ 520, 4 ]
[ 562, 32 ]
python
en
['en', 'en', 'en']
True
LegacyMetadata.todict
(self, skip_missing=False)
Return fields as a dict. Field names will be converted to use the underscore-lowercase style instead of hyphen-mixed case (i.e. home_page instead of Home-page).
Return fields as a dict.
def todict(self, skip_missing=False): """Return fields as a dict. Field names will be converted to use the underscore-lowercase style instead of hyphen-mixed case (i.e. home_page instead of Home-page). """ self.set_metadata_version() mapping_1_0 = ( ('metada...
[ "def", "todict", "(", "self", ",", "skip_missing", "=", "False", ")", ":", "self", ".", "set_metadata_version", "(", ")", "mapping_1_0", "=", "(", "(", "'metadata_version'", ",", "'Metadata-Version'", ")", ",", "(", "'name'", ",", "'Name'", ")", ",", "(", ...
[ 564, 4 ]
[ 621, 19 ]
python
en
['en', 'en', 'en']
True
Metadata.get_requirements
(self, reqts, extras=None, env=None)
Base method to get dependencies, given a set of extras to satisfy and an optional environment context. :param reqts: A list of sometimes-wanted dependencies, perhaps dependent on extras and environment. :param extras: A list of optional components being requested. ...
Base method to get dependencies, given a set of extras to satisfy and an optional environment context. :param reqts: A list of sometimes-wanted dependencies, perhaps dependent on extras and environment. :param extras: A list of optional components being requested. ...
def get_requirements(self, reqts, extras=None, env=None): """ Base method to get dependencies, given a set of extras to satisfy and an optional environment context. :param reqts: A list of sometimes-wanted dependencies, perhaps dependent on extras and environment. ...
[ "def", "get_requirements", "(", "self", ",", "reqts", ",", "extras", "=", "None", ",", "env", "=", "None", ")", ":", "if", "self", ".", "_legacy", ":", "result", "=", "reqts", "else", ":", "result", "=", "[", "]", "extras", "=", "get_extras", "(", ...
[ 881, 4 ]
[ 921, 21 ]
python
en
['en', 'error', 'th']
False
ScanningLoader.loadTestsFromModule
(self, module, pattern=None)
Return a suite of all tests cases contained in the given module If the module is a package, load tests from all the modules in it. If the module has an ``additional_tests`` function, call it and add the return value to the tests.
Return a suite of all tests cases contained in the given module
def loadTestsFromModule(self, module, pattern=None): """Return a suite of all tests cases contained in the given module If the module is a package, load tests from all the modules in it. If the module has an ``additional_tests`` function, call it and add the return value to the tests. ...
[ "def", "loadTestsFromModule", "(", "self", ",", "module", ",", "pattern", "=", "None", ")", ":", "if", "module", "in", "self", ".", "_visited", ":", "return", "None", "self", ".", "_visited", ".", "add", "(", "module", ")", "tests", "=", "[", "]", "t...
[ 28, 4 ]
[ 59, 27 ]
python
en
['en', 'en', 'en']
True
test.with_project_on_sys_path
(self, func)
Backward compatibility for project_on_sys_path context.
Backward compatibility for project_on_sys_path context.
def with_project_on_sys_path(self, func): """ Backward compatibility for project_on_sys_path context. """ with self.project_on_sys_path(): func()
[ "def", "with_project_on_sys_path", "(", "self", ",", "func", ")", ":", "with", "self", ".", "project_on_sys_path", "(", ")", ":", "func", "(", ")" ]
[ 122, 4 ]
[ 127, 18 ]
python
en
['en', 'error', 'th']
False
test.paths_on_pythonpath
(paths)
Add the indicated paths to the head of the PYTHONPATH environment variable so that subprocesses will also see the packages at these paths. Do this in a context that restores the value on exit.
Add the indicated paths to the head of the PYTHONPATH environment variable so that subprocesses will also see the packages at these paths.
def paths_on_pythonpath(paths): """ Add the indicated paths to the head of the PYTHONPATH environment variable so that subprocesses will also see the packages at these paths. Do this in a context that restores the value on exit. """ nothing = object() ori...
[ "def", "paths_on_pythonpath", "(", "paths", ")", ":", "nothing", "=", "object", "(", ")", "orig_pythonpath", "=", "os", ".", "environ", ".", "get", "(", "'PYTHONPATH'", ",", "nothing", ")", "current_pythonpath", "=", "os", ".", "environ", ".", "get", "(", ...
[ 178, 4 ]
[ 200, 58 ]
python
en
['en', 'error', 'th']
False
test.install_dists
(dist)
Install the requirements indicated by self.distribution and return an iterable of the dists that were built.
Install the requirements indicated by self.distribution and return an iterable of the dists that were built.
def install_dists(dist): """ Install the requirements indicated by self.distribution and return an iterable of the dists that were built. """ ir_d = dist.fetch_build_eggs(dist.install_requires) tr_d = dist.fetch_build_eggs(dist.tests_require or []) er_d = dist.fet...
[ "def", "install_dists", "(", "dist", ")", ":", "ir_d", "=", "dist", ".", "fetch_build_eggs", "(", "dist", ".", "install_requires", ")", "tr_d", "=", "dist", ".", "fetch_build_eggs", "(", "dist", ".", "tests_require", "or", "[", "]", ")", "er_d", "=", "di...
[ 203, 4 ]
[ 214, 48 ]
python
en
['en', 'error', 'th']
False
test._resolve_as_ep
(val)
Load the indicated attribute value, called, as a as if it were specified as an entry point.
Load the indicated attribute value, called, as a as if it were specified as an entry point.
def _resolve_as_ep(val): """ Load the indicated attribute value, called, as a as if it were specified as an entry point. """ if val is None: return parsed = EntryPoint.parse("x=" + val) return parsed.resolve()()
[ "def", "_resolve_as_ep", "(", "val", ")", ":", "if", "val", "is", "None", ":", "return", "parsed", "=", "EntryPoint", ".", "parse", "(", "\"x=\"", "+", "val", ")", "return", "parsed", ".", "resolve", "(", ")", "(", ")" ]
[ 271, 4 ]
[ 279, 33 ]
python
en
['en', 'error', 'th']
False
Deserializer
(stream_or_string, **options)
Deserialize a stream or string of YAML data.
Deserialize a stream or string of YAML data.
def Deserializer(stream_or_string, **options): """ Deserialize a stream or string of YAML data. """ if isinstance(stream_or_string, bytes): stream_or_string = stream_or_string.decode('utf-8') if isinstance(stream_or_string, six.string_types): stream = StringIO(stream_or_string) e...
[ "def", "Deserializer", "(", "stream_or_string", ",", "*", "*", "options", ")", ":", "if", "isinstance", "(", "stream_or_string", ",", "bytes", ")", ":", "stream_or_string", "=", "stream_or_string", ".", "decode", "(", "'utf-8'", ")", "if", "isinstance", "(", ...
[ 59, 0 ]
[ 76, 85 ]
python
en
['en', 'error', 'th']
False
is_canarytoken
(message: Dict[str, Any])
Requests sent from Thinkst canaries are either from canarytokens or canaries, which can be differentiated by the value of the `AlertType` field.
Requests sent from Thinkst canaries are either from canarytokens or canaries, which can be differentiated by the value of the `AlertType` field.
def is_canarytoken(message: Dict[str, Any]) -> bool: """ Requests sent from Thinkst canaries are either from canarytokens or canaries, which can be differentiated by the value of the `AlertType` field. """ return message["AlertType"] == "CanarytokenIncident"
[ "def", "is_canarytoken", "(", "message", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "bool", ":", "return", "message", "[", "\"AlertType\"", "]", "==", "\"CanarytokenIncident\"" ]
[ 12, 0 ]
[ 18, 56 ]
python
en
['en', 'error', 'th']
False
canary_name
(message: Dict[str, Any])
Returns the name of the canary or canarytoken.
Returns the name of the canary or canarytoken.
def canary_name(message: Dict[str, Any]) -> str: """ Returns the name of the canary or canarytoken. """ if is_canarytoken(message): return message["Reminder"] else: return message["CanaryName"]
[ "def", "canary_name", "(", "message", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "str", ":", "if", "is_canarytoken", "(", "message", ")", ":", "return", "message", "[", "\"Reminder\"", "]", "else", ":", "return", "message", "[", "\"CanaryName\"...
[ 21, 0 ]
[ 28, 36 ]
python
en
['en', 'error', 'th']
False
canary_kind
(message: Dict[str, Any])
Returns a description of the kind of request - canary or canarytoken.
Returns a description of the kind of request - canary or canarytoken.
def canary_kind(message: Dict[str, Any]) -> str: """ Returns a description of the kind of request - canary or canarytoken. """ if is_canarytoken(message): return "canarytoken" else: return "canary"
[ "def", "canary_kind", "(", "message", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "str", ":", "if", "is_canarytoken", "(", "message", ")", ":", "return", "\"canarytoken\"", "else", ":", "return", "\"canary\"" ]
[ 31, 0 ]
[ 38, 23 ]
python
en
['en', 'error', 'th']
False
source_ip_and_reverse_dns
(message: Dict[str, Any])
Extract the source IP and reverse DNS information from a canary request.
Extract the source IP and reverse DNS information from a canary request.
def source_ip_and_reverse_dns(message: Dict[str, Any]) -> Tuple[Optional[str], Optional[str]]: """ Extract the source IP and reverse DNS information from a canary request. """ reverse_dns, source_ip = (None, None) if "SourceIP" in message: source_ip = message["SourceIP"] # `ReverseDNS` ...
[ "def", "source_ip_and_reverse_dns", "(", "message", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Tuple", "[", "Optional", "[", "str", "]", ",", "Optional", "[", "str", "]", "]", ":", "reverse_dns", ",", "source_ip", "=", "(", "None", ",", "N...
[ 41, 0 ]
[ 53, 35 ]
python
en
['en', 'error', 'th']
False
body
(message: Dict[str, Any])
Construct the response to a canary or canarytoken request.
Construct the response to a canary or canarytoken request.
def body(message: Dict[str, Any]) -> str: """ Construct the response to a canary or canarytoken request. """ title = canary_kind(message).title() name = canary_name(message) body = f"**:alert: {title} *{name}* has been triggered!**\n\n{message['Intro']}\n\n" if "IncidentHash" in message: ...
[ "def", "body", "(", "message", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "str", ":", "title", "=", "canary_kind", "(", "message", ")", ".", "title", "(", ")", "name", "=", "canary_name", "(", "message", ")", "body", "=", "f\"**:alert: {tit...
[ 56, 0 ]
[ 102, 15 ]
python
en
['en', 'error', 'th']
False
api_thinkst_webhook
( request: HttpRequest, user_profile: UserProfile, message: Dict[str, Any] = REQ(argument_type="body"), user_specified_topic: Optional[str] = REQ("topic", default=None), )
Construct a response to a webhook event from a Thinkst canary or canarytoken. Thinkst offers public canarytokens with canarytokens.org and with their canary product, but the schema returned by these identically named services are completely different - canarytokens from canarytokens.org are handled by...
Construct a response to a webhook event from a Thinkst canary or canarytoken.
def api_thinkst_webhook( request: HttpRequest, user_profile: UserProfile, message: Dict[str, Any] = REQ(argument_type="body"), user_specified_topic: Optional[str] = REQ("topic", default=None), ) -> HttpResponse: """ Construct a response to a webhook event from a Thinkst canary or canarytoken. ...
[ "def", "api_thinkst_webhook", "(", "request", ":", "HttpRequest", ",", "user_profile", ":", "UserProfile", ",", "message", ":", "Dict", "[", "str", ",", "Any", "]", "=", "REQ", "(", "argument_type", "=", "\"body\"", ")", ",", "user_specified_topic", ":", "Op...
[ 107, 0 ]
[ 139, 25 ]
python
en
['en', 'error', 'th']
False
__init__
(self, row, col, d)
Initialize Kohonen Neuron. Args: row (int): Row coordinate of the neuron in the network. col (int): Column coordinate of the neuron the network. d (int): Length of the dimension of the input.
Initialize Kohonen Neuron.
def __init__(self, row, col, d): """ Initialize Kohonen Neuron. Args: row (int): Row coordinate of the neuron in the network. col (int): Column coordinate of the neuron the network. d (int): Length of the dimension of the input. """ self.row =...
[ "def", "__init__", "(", "self", ",", "row", ",", "col", ",", "d", ")", ":", "self", ".", "row", "=", "row", "self", ".", "col", "=", "col", "self", ".", "W", "=", "2", "*", "np", ".", "random", ".", "random", "(", "size", "=", "(", "d", ","...
[ 10, 4 ]
[ 21, 53 ]
python
en
['en', 'error', 'th']
False
_lazy_re_compile
(regex, flags=0)
Lazily compile a regex with flags.
Lazily compile a regex with flags.
def _lazy_re_compile(regex, flags=0): """Lazily compile a regex with flags.""" def _compile(): # Compile the regex if it was not passed pre-compiled. if isinstance(regex, str): return re.compile(regex, flags) else: assert not flags, "flags must be empty if regex i...
[ "def", "_lazy_re_compile", "(", "regex", ",", "flags", "=", "0", ")", ":", "def", "_compile", "(", ")", ":", "# Compile the regex if it was not passed pre-compiled.", "if", "isinstance", "(", "regex", ",", "str", ")", ":", "return", "re", ".", "compile", "(", ...
[ 16, 0 ]
[ 25, 37 ]
python
en
['en', 'en', 'en']
True
ip_address_validators
(protocol, unpack_ipv4)
Depending on the given parameters, return the appropriate validators for the GenericIPAddressField.
Depending on the given parameters, return the appropriate validators for the GenericIPAddressField.
def ip_address_validators(protocol, unpack_ipv4): """ Depending on the given parameters, return the appropriate validators for the GenericIPAddressField. """ if protocol != 'both' and unpack_ipv4: raise ValueError( "You can only use `unpack_ipv4` if `protocol` is set to 'both'") ...
[ "def", "ip_address_validators", "(", "protocol", ",", "unpack_ipv4", ")", ":", "if", "protocol", "!=", "'both'", "and", "unpack_ipv4", ":", "raise", "ValueError", "(", "\"You can only use `unpack_ipv4` if `protocol` is set to 'both'\"", ")", "try", ":", "return", "ip_ad...
[ 280, 0 ]
[ 292, 70 ]
python
en
['en', 'error', 'th']
False
Field.clean
(self, value)
Validate the given value and return its "cleaned" value as an appropriate Python object. Raise ValidationError for any errors.
Validate the given value and return its "cleaned" value as an appropriate Python object. Raise ValidationError for any errors.
def clean(self, value): """ Validate the given value and return its "cleaned" value as an appropriate Python object. Raise ValidationError for any errors. """ value = self.to_python(value) self.validate(value) self.run_validators(value) return value
[ "def", "clean", "(", "self", ",", "value", ")", ":", "value", "=", "self", ".", "to_python", "(", "value", ")", "self", ".", "validate", "(", "value", ")", "self", ".", "run_validators", "(", "value", ")", "return", "value" ]
[ 142, 4 ]
[ 150, 20 ]
python
en
['en', 'error', 'th']
False
Field.bound_data
(self, data, initial)
Return the value that should be shown for this field on render of a bound form, given the submitted POST data for the field and the initial data, if any. For most fields, this will simply be data; FileFields need to handle it a bit differently.
Return the value that should be shown for this field on render of a bound form, given the submitted POST data for the field and the initial data, if any.
def bound_data(self, data, initial): """ Return the value that should be shown for this field on render of a bound form, given the submitted POST data for the field and the initial data, if any. For most fields, this will simply be data; FileFields need to handle it a bi...
[ "def", "bound_data", "(", "self", ",", "data", ",", "initial", ")", ":", "if", "self", ".", "disabled", ":", "return", "initial", "return", "data" ]
[ 152, 4 ]
[ 163, 19 ]
python
en
['en', 'error', 'th']
False
Field.widget_attrs
(self, widget)
Given a Widget instance (*not* a Widget class), return a dictionary of any HTML attributes that should be added to the Widget, based on this Field.
Given a Widget instance (*not* a Widget class), return a dictionary of any HTML attributes that should be added to the Widget, based on this Field.
def widget_attrs(self, widget): """ Given a Widget instance (*not* a Widget class), return a dictionary of any HTML attributes that should be added to the Widget, based on this Field. """ return {}
[ "def", "widget_attrs", "(", "self", ",", "widget", ")", ":", "return", "{", "}" ]
[ 165, 4 ]
[ 171, 17 ]
python
en
['en', 'error', 'th']
False
Field.has_changed
(self, initial, data)
Return True if data differs from initial.
Return True if data differs from initial.
def has_changed(self, initial, data): """Return True if data differs from initial.""" # Always return False if the field is disabled since self.bound_data # always uses the initial value in this case. if self.disabled: return False try: data = self.to_pyth...
[ "def", "has_changed", "(", "self", ",", "initial", ",", "data", ")", ":", "# Always return False if the field is disabled since self.bound_data", "# always uses the initial value in this case.", "if", "self", ".", "disabled", ":", "return", "False", "try", ":", "data", "=...
[ 173, 4 ]
[ 190, 42 ]
python
en
['en', 'en', 'en']
True
Field.get_bound_field
(self, form, field_name)
Return a BoundField instance that will be used when accessing the form field in a template.
Return a BoundField instance that will be used when accessing the form field in a template.
def get_bound_field(self, form, field_name): """ Return a BoundField instance that will be used when accessing the form field in a template. """ return BoundField(form, self, field_name)
[ "def", "get_bound_field", "(", "self", ",", "form", ",", "field_name", ")", ":", "return", "BoundField", "(", "form", ",", "self", ",", "field_name", ")" ]
[ 192, 4 ]
[ 197, 49 ]
python
en
['en', 'error', 'th']
False
CharField.to_python
(self, value)
Return a string.
Return a string.
def to_python(self, value): """Return a string.""" if value not in self.empty_values: value = str(value) if self.strip: value = value.strip() if value in self.empty_values: return self.empty_value return value
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "not", "in", "self", ".", "empty_values", ":", "value", "=", "str", "(", "value", ")", "if", "self", ".", "strip", ":", "value", "=", "value", ".", "strip", "(", ")", "if", "...
[ 221, 4 ]
[ 229, 20 ]
python
en
['en', 'cy', 'en']
True
IntegerField.to_python
(self, value)
Validate that int() can be called on the input. Return the result of int() or None for empty values.
Validate that int() can be called on the input. Return the result of int() or None for empty values.
def to_python(self, value): """ Validate that int() can be called on the input. Return the result of int() or None for empty values. """ value = super().to_python(value) if value in self.empty_values: return None if self.localize: value = f...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "value", "=", "super", "(", ")", ".", "to_python", "(", "value", ")", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "self", ".", "localize", ":", "value", "=", ...
[ 261, 4 ]
[ 276, 20 ]
python
en
['en', 'error', 'th']
False
FloatField.to_python
(self, value)
Validate that float() can be called on the input. Return the result of float() or None for empty values.
Validate that float() can be called on the input. Return the result of float() or None for empty values.
def to_python(self, value): """ Validate that float() can be called on the input. Return the result of float() or None for empty values. """ value = super(IntegerField, self).to_python(value) if value in self.empty_values: return None if self.localize:...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "value", "=", "super", "(", "IntegerField", ",", "self", ")", ".", "to_python", "(", "value", ")", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "self", ".", "l...
[ 293, 4 ]
[ 307, 20 ]
python
en
['en', 'error', 'th']
False
DecimalField.to_python
(self, value)
Validate that the input is a decimal number. Return a Decimal instance or None for empty values. Ensure that there are no more than max_digits in the number and no more than decimal_places digits after the decimal point.
Validate that the input is a decimal number. Return a Decimal instance or None for empty values. Ensure that there are no more than max_digits in the number and no more than decimal_places digits after the decimal point.
def to_python(self, value): """ Validate that the input is a decimal number. Return a Decimal instance or None for empty values. Ensure that there are no more than max_digits in the number and no more than decimal_places digits after the decimal point. """ if valu...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "self", ".", "localize", ":", "value", "=", "formats", ".", "sanitize_separators", "(", "value", ")", "value", "=", ...
[ 333, 4 ]
[ 349, 20 ]
python
en
['en', 'error', 'th']
False
DateField.to_python
(self, value)
Validate that the input can be converted to a date. Return a Python datetime.date object.
Validate that the input can be converted to a date. Return a Python datetime.date object.
def to_python(self, value): """ Validate that the input can be converted to a date. Return a Python datetime.date object. """ if value in self.empty_values: return None if isinstance(value, datetime.datetime): return value.date() if isinsta...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "value", ".", "date", "(", ")", ...
[ 399, 4 ]
[ 410, 39 ]
python
en
['en', 'error', 'th']
False
TimeField.to_python
(self, value)
Validate that the input can be converted to a time. Return a Python datetime.time object.
Validate that the input can be converted to a time. Return a Python datetime.time object.
def to_python(self, value): """ Validate that the input can be converted to a time. Return a Python datetime.time object. """ if value in self.empty_values: return None if isinstance(value, datetime.time): return value return super().to_pyt...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "isinstance", "(", "value", ",", "datetime", ".", "time", ")", ":", "return", "value", "return", "super", "(", ")", ...
[ 423, 4 ]
[ 432, 39 ]
python
en
['en', 'error', 'th']
False