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
GoogleZoom.__len__
(self)
Returns the number of zoom levels.
Returns the number of zoom levels.
def __len__(self): "Returns the number of zoom levels." return self._nzoom
[ "def", "__len__", "(", "self", ")", ":", "return", "self", ".", "_nzoom" ]
[ 53, 4 ]
[ 55, 26 ]
python
en
['en', 'en', 'en']
True
GoogleZoom.get_lon_lat
(self, lonlat)
Unpacks longitude, latitude from GEOS Points and 2-tuples.
Unpacks longitude, latitude from GEOS Points and 2-tuples.
def get_lon_lat(self, lonlat): "Unpacks longitude, latitude from GEOS Points and 2-tuples." if isinstance(lonlat, Point): lon, lat = lonlat.coords else: lon, lat = lonlat return lon, lat
[ "def", "get_lon_lat", "(", "self", ",", "lonlat", ")", ":", "if", "isinstance", "(", "lonlat", ",", "Point", ")", ":", "lon", ",", "lat", "=", "lonlat", ".", "coords", "else", ":", "lon", ",", "lat", "=", "lonlat", "return", "lon", ",", "lat" ]
[ 57, 4 ]
[ 63, 23 ]
python
en
['en', 'zu', 'en']
True
GoogleZoom.lonlat_to_pixel
(self, lonlat, zoom)
Converts a longitude, latitude coordinate pair for the given zoom level.
Converts a longitude, latitude coordinate pair for the given zoom level.
def lonlat_to_pixel(self, lonlat, zoom): "Converts a longitude, latitude coordinate pair for the given zoom level." # Setting up, unpacking the longitude, latitude values and getting the # number of pixels for the given zoom level. lon, lat = self.get_lon_lat(lonlat) npix = self....
[ "def", "lonlat_to_pixel", "(", "self", ",", "lonlat", ",", "zoom", ")", ":", "# Setting up, unpacking the longitude, latitude values and getting the", "# number of pixels for the given zoom level.", "lon", ",", "lat", "=", "self", ".", "get_lon_lat", "(", "lonlat", ")", "...
[ 65, 4 ]
[ 86, 27 ]
python
en
['en', 'en', 'en']
True
GoogleZoom.pixel_to_lonlat
(self, px, zoom)
Converts a pixel to a longitude, latitude pair at the given zoom level.
Converts a pixel to a longitude, latitude pair at the given zoom level.
def pixel_to_lonlat(self, px, zoom): "Converts a pixel to a longitude, latitude pair at the given zoom level." if len(px) != 2: raise TypeError('Pixel should be a sequence of two elements.') # Getting the number of pixels for the given zoom level. npix = self._npix[zoom] ...
[ "def", "pixel_to_lonlat", "(", "self", ",", "px", ",", "zoom", ")", ":", "if", "len", "(", "px", ")", "!=", "2", ":", "raise", "TypeError", "(", "'Pixel should be a sequence of two elements.'", ")", "# Getting the number of pixels for the given zoom level.", "npix", ...
[ 88, 4 ]
[ 103, 25 ]
python
en
['en', 'en', 'en']
True
GoogleZoom.tile
(self, lonlat, zoom)
Returns a Polygon corresponding to the region represented by a fictional Google Tile for the given longitude/latitude pair and zoom level. This tile is used to determine the size of a tile at the given point.
Returns a Polygon corresponding to the region represented by a fictional Google Tile for the given longitude/latitude pair and zoom level. This tile is used to determine the size of a tile at the given point.
def tile(self, lonlat, zoom): """ Returns a Polygon corresponding to the region represented by a fictional Google Tile for the given longitude/latitude pair and zoom level. This tile is used to determine the size of a tile at the given point. """ # The given lonlat is th...
[ "def", "tile", "(", "self", ",", "lonlat", ",", "zoom", ")", ":", "# The given lonlat is the center of the tile.", "delta", "=", "self", ".", "_tilesize", "/", "2", "# Getting the pixel coordinates corresponding to the", "# the longitude/latitude.", "px", "=", "self", "...
[ 105, 4 ]
[ 124, 89 ]
python
en
['en', 'error', 'th']
False
GoogleZoom.get_zoom
(self, geom)
Returns the optimal Zoom level for the given geometry.
Returns the optimal Zoom level for the given geometry.
def get_zoom(self, geom): "Returns the optimal Zoom level for the given geometry." # Checking the input type. if not isinstance(geom, GEOSGeometry) or geom.srid != 4326: raise TypeError('get_zoom() expects a GEOS Geometry with an SRID of 4326.') # Getting the envelope for th...
[ "def", "get_zoom", "(", "self", ",", "geom", ")", ":", "# Checking the input type.", "if", "not", "isinstance", "(", "geom", ",", "GEOSGeometry", ")", "or", "geom", ".", "srid", "!=", "4326", ":", "raise", "TypeError", "(", "'get_zoom() expects a GEOS Geometry w...
[ 126, 4 ]
[ 150, 30 ]
python
en
['en', 'en', 'en']
True
GoogleZoom.get_width_height
(self, extent)
Returns the width and height for the given extent.
Returns the width and height for the given extent.
def get_width_height(self, extent): """ Returns the width and height for the given extent. """ # Getting the lower-left, upper-left, and upper-right # coordinates from the extent. ll = Point(extent[:2]) ul = Point(extent[0], extent[3]) ur = Point(extent[2:...
[ "def", "get_width_height", "(", "self", ",", "extent", ")", ":", "# Getting the lower-left, upper-left, and upper-right", "# coordinates from the extent.", "ll", "=", "Point", "(", "extent", "[", ":", "2", "]", ")", "ul", "=", "Point", "(", "extent", "[", "0", "...
[ 152, 4 ]
[ 164, 28 ]
python
en
['en', 'error', 'th']
False
BaseAction.verify_action
( self, action: Callable[[], object], *, event_types: Optional[List[str]] = None, include_subscribers: bool = True, state_change_expected: bool = True, notification_settings_null: bool = False, client_gravatar: bool = True, user_avatar_url_field_op...
Make sure we have a clean slate of client descriptors for these tests. If we don't do this, then certain failures will only manifest when you run multiple tests within a single test function. See also https://zulip.readthedocs.io/en/latest/subsystems/events-system.html#testing ...
Make sure we have a clean slate of client descriptors for these tests. If we don't do this, then certain failures will only manifest when you run multiple tests within a single test function.
def verify_action( self, action: Callable[[], object], *, event_types: Optional[List[str]] = None, include_subscribers: bool = True, state_change_expected: bool = True, notification_settings_null: bool = False, client_gravatar: bool = True, user_av...
[ "def", "verify_action", "(", "self", ",", "action", ":", "Callable", "[", "[", "]", ",", "object", "]", ",", "*", ",", "event_types", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ",", "include_subscribers", ":", "bool", "=", "True...
[ 213, 4 ]
[ 317, 21 ]
python
en
['en', 'error', 'th']
False
NormalActionsTest.test_do_delete_message_stream_legacy
(self)
Test for legacy method of deleting messages which sends an event per message to delete to the client.
Test for legacy method of deleting messages which sends an event per message to delete to the client.
def test_do_delete_message_stream_legacy(self) -> None: """ Test for legacy method of deleting messages which sends an event per message to delete to the client. """ hamlet = self.example_user("hamlet") msg_id = self.send_stream_message(hamlet, "Verona") msg_id_2 ...
[ "def", "test_do_delete_message_stream_legacy", "(", "self", ")", "->", "None", ":", "hamlet", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "msg_id", "=", "self", ".", "send_stream_message", "(", "hamlet", ",", "\"Verona\"", ")", "msg_id_2", "=", "...
[ 1642, 4 ]
[ 1663, 9 ]
python
en
['en', 'error', 'th']
False
UserDisplayActionTest.do_set_user_display_settings_test
(self, setting_name: str)
Test updating each setting in UserProfile.property_types dict.
Test updating each setting in UserProfile.property_types dict.
def do_set_user_display_settings_test(self, setting_name: str) -> None: """Test updating each setting in UserProfile.property_types dict.""" test_changes: Dict[str, Any] = dict( emojiset=["twitter"], default_language=["es", "de", "en"], default_view=["all_messages", ...
[ "def", "do_set_user_display_settings_test", "(", "self", ",", "setting_name", ":", "str", ")", "->", "None", ":", "test_changes", ":", "Dict", "[", "str", ",", "Any", "]", "=", "dict", "(", "emojiset", "=", "[", "\"twitter\"", "]", ",", "default_language", ...
[ 1945, 4 ]
[ 1981, 75 ]
python
en
['en', 'en', 'en']
True
read_setup_file
(filename)
Reads a Setup file and returns Extension instances.
Reads a Setup file and returns Extension instances.
def read_setup_file(filename): """Reads a Setup file and returns Extension instances.""" from distutils.sysconfig import (parse_makefile, expand_makefile_vars, _variable_rx) from distutils.text_file import TextFile from distutils.util import split_quoted # Firs...
[ "def", "read_setup_file", "(", "filename", ")", ":", "from", "distutils", ".", "sysconfig", "import", "(", "parse_makefile", ",", "expand_makefile_vars", ",", "_variable_rx", ")", "from", "distutils", ".", "text_file", "import", "TextFile", "from", "distutils", "....
[ 140, 0 ]
[ 239, 21 ]
python
en
['en', 'en', 'en']
True
AuthenticationForm.__init__
(self, request=None, *args, **kwargs)
The 'request' parameter is set for custom auth use by subclasses. The form data comes in via the standard 'data' kwarg.
The 'request' parameter is set for custom auth use by subclasses. The form data comes in via the standard 'data' kwarg.
def __init__(self, request=None, *args, **kwargs): """ The 'request' parameter is set for custom auth use by subclasses. The form data comes in via the standard 'data' kwarg. """ self.request = request self.user_cache = None super(AuthenticationForm, self).__init_...
[ "def", "__init__", "(", "self", ",", "request", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "request", "=", "request", "self", ".", "user_cache", "=", "None", "super", "(", "AuthenticationForm", ",", "self", ")", "....
[ 143, 4 ]
[ 156, 86 ]
python
en
['en', 'error', 'th']
False
AuthenticationForm.confirm_login_allowed
(self, user)
Controls whether the given User may log in. This is a policy setting, independent of end-user authentication. This default behavior is to allow login by active users, and reject login by inactive users. If the given user cannot log in, this method should raise a ``forms.Validat...
Controls whether the given User may log in. This is a policy setting, independent of end-user authentication. This default behavior is to allow login by active users, and reject login by inactive users.
def confirm_login_allowed(self, user): """ Controls whether the given User may log in. This is a policy setting, independent of end-user authentication. This default behavior is to allow login by active users, and reject login by inactive users. If the given user cannot log in, ...
[ "def", "confirm_login_allowed", "(", "self", ",", "user", ")", ":", "if", "not", "user", ".", "is_active", ":", "raise", "forms", ".", "ValidationError", "(", "self", ".", "error_messages", "[", "'inactive'", "]", ",", "code", "=", "'inactive'", ",", ")" ]
[ 176, 4 ]
[ 191, 13 ]
python
en
['en', 'error', 'th']
False
PasswordResetForm.send_mail
(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None)
Sends a django.core.mail.EmailMultiAlternatives to `to_email`.
Sends a django.core.mail.EmailMultiAlternatives to `to_email`.
def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): """ Sends a django.core.mail.EmailMultiAlternatives to `to_email`. """ subject = loader.render_to_string(subject_template_name, context) ...
[ "def", "send_mail", "(", "self", ",", "subject_template_name", ",", "email_template_name", ",", "context", ",", "from_email", ",", "to_email", ",", "html_email_template_name", "=", "None", ")", ":", "subject", "=", "loader", ".", "render_to_string", "(", "subject_...
[ 205, 4 ]
[ 220, 28 ]
python
en
['en', 'error', 'th']
False
PasswordResetForm.get_users
(self, email)
Given an email, return matching user(s) who should receive a reset. This allows subclasses to more easily customize the default policies that prevent inactive users and users with unusable passwords from resetting their password.
Given an email, return matching user(s) who should receive a reset.
def get_users(self, email): """Given an email, return matching user(s) who should receive a reset. This allows subclasses to more easily customize the default policies that prevent inactive users and users with unusable passwords from resetting their password. """ activ...
[ "def", "get_users", "(", "self", ",", "email", ")", ":", "active_users", "=", "get_user_model", "(", ")", ".", "_default_manager", ".", "filter", "(", "email__iexact", "=", "email", ",", "is_active", "=", "True", ")", "return", "(", "u", "for", "u", "in"...
[ 222, 4 ]
[ 232, 67 ]
python
en
['en', 'en', 'en']
True
PasswordResetForm.save
(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, from_email=None, request=None, html_email_template_nam...
Generates a one-use only link for resetting password and sends to the user.
Generates a one-use only link for resetting password and sends to the user.
def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, from_email=None, request=None, html_email_temp...
[ "def", "save", "(", "self", ",", "domain_override", "=", "None", ",", "subject_template_name", "=", "'registration/password_reset_subject.txt'", ",", "email_template_name", "=", "'registration/password_reset_email.html'", ",", "use_https", "=", "False", ",", "token_generato...
[ 234, 4 ]
[ 263, 77 ]
python
en
['en', 'error', 'th']
False
PasswordChangeForm.clean_old_password
(self)
Validates that the old_password field is correct.
Validates that the old_password field is correct.
def clean_old_password(self): """ Validates that the old_password field is correct. """ old_password = self.cleaned_data["old_password"] if not self.user.check_password(old_password): raise forms.ValidationError( self.error_messages['password_incorrect...
[ "def", "clean_old_password", "(", "self", ")", ":", "old_password", "=", "self", ".", "cleaned_data", "[", "\"old_password\"", "]", "if", "not", "self", ".", "user", ".", "check_password", "(", "old_password", ")", ":", "raise", "forms", ".", "ValidationError"...
[ 313, 4 ]
[ 323, 27 ]
python
en
['en', 'error', 'th']
False
AdminPasswordChangeForm.save
(self, commit=True)
Saves the new password.
Saves the new password.
def save(self, commit=True): """ Saves the new password. """ self.user.set_password(self.cleaned_data["password1"]) if commit: self.user.save() return self.user
[ "def", "save", "(", "self", ",", "commit", "=", "True", ")", ":", "self", ".", "user", ".", "set_password", "(", "self", ".", "cleaned_data", "[", "\"password1\"", "]", ")", "if", "commit", ":", "self", ".", "user", ".", "save", "(", ")", "return", ...
[ 359, 4 ]
[ 366, 24 ]
python
en
['en', 'error', 'th']
False
find_log_caller_module
(record: logging.LogRecord)
Find the module name corresponding to where this record was logged. Sadly `record.module` is just the innermost component of the full module name, so we have to go reconstruct this ourselves.
Find the module name corresponding to where this record was logged.
def find_log_caller_module(record: logging.LogRecord) -> Optional[str]: """Find the module name corresponding to where this record was logged. Sadly `record.module` is just the innermost component of the full module name, so we have to go reconstruct this ourselves. """ # Repeat a search similar to...
[ "def", "find_log_caller_module", "(", "record", ":", "logging", ".", "LogRecord", ")", "->", "Optional", "[", "str", "]", ":", "# Repeat a search similar to that in logging.Logger.findCaller.", "# The logging call should still be on the stack somewhere; search until", "# we find so...
[ 143, 0 ]
[ 159, 20 ]
python
en
['en', 'en', 'en']
True
log_to_file
( logger: Logger, filename: str, log_format: str = "%(asctime)s %(levelname)-8s %(message)s", )
Note: `filename` should be declared in zproject/computed_settings.py with zulip_path.
Note: `filename` should be declared in zproject/computed_settings.py with zulip_path.
def log_to_file( logger: Logger, filename: str, log_format: str = "%(asctime)s %(levelname)-8s %(message)s", ) -> None: """Note: `filename` should be declared in zproject/computed_settings.py with zulip_path.""" formatter = logging.Formatter(log_format) handler = logging.FileHandler(filename) ...
[ "def", "log_to_file", "(", "logger", ":", "Logger", ",", "filename", ":", "str", ",", "log_format", ":", "str", "=", "\"%(asctime)s %(levelname)-8s %(message)s\"", ",", ")", "->", "None", ":", "formatter", "=", "logging", ".", "Formatter", "(", "log_format", "...
[ 288, 0 ]
[ 297, 30 ]
python
en
['en', 'en', 'en']
True
GDALRasterBase.metadata
(self)
Return the metadata for this raster or band. The return value is a nested dictionary, where the first-level key is the metadata domain and the second-level is the metadata item names and values for that domain.
Return the metadata for this raster or band. The return value is a nested dictionary, where the first-level key is the metadata domain and the second-level is the metadata item names and values for that domain.
def metadata(self): """ Return the metadata for this raster or band. The return value is a nested dictionary, where the first-level key is the metadata domain and the second-level is the metadata item names and values for that domain. """ # The initial metadata domain lis...
[ "def", "metadata", "(", "self", ")", ":", "# The initial metadata domain list contains the default domain.", "# The default is returned if domain name is None.", "domain_list", "=", "[", "'DEFAULT'", "]", "# Get additional metadata domains from the raster.", "meta_list", "=", "capi",...
[ 9, 4 ]
[ 56, 21 ]
python
en
['en', 'error', 'th']
False
GDALRasterBase.metadata
(self, value)
Set the metadata. Update only the domains that are contained in the value dictionary.
Set the metadata. Update only the domains that are contained in the value dictionary.
def metadata(self, value): """ Set the metadata. Update only the domains that are contained in the value dictionary. """ # Loop through domains. for domain, metadata in value.items(): # Set the domain to None for the default, otherwise encode. doma...
[ "def", "metadata", "(", "self", ",", "value", ")", ":", "# Loop through domains.", "for", "domain", ",", "metadata", "in", "value", ".", "items", "(", ")", ":", "# Set the domain to None for the default, otherwise encode.", "domain", "=", "None", "if", "domain", "...
[ 59, 4 ]
[ 74, 17 ]
python
en
['en', 'error', 'th']
False
SignalTests.test_disconnect_in_dispatch
(self)
Test that signals that disconnect when being called don't mess future dispatching.
Test that signals that disconnect when being called don't mess future dispatching.
def test_disconnect_in_dispatch(self): """ Test that signals that disconnect when being called don't mess future dispatching. """ class Handler(object): def __init__(self, param): self.param = param self._run = False def _...
[ "def", "test_disconnect_in_dispatch", "(", "self", ")", ":", "class", "Handler", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "param", ")", ":", "self", ".", "param", "=", "param", "self", ".", "_run", "=", "False", "def", "__call__", ...
[ 220, 4 ]
[ 242, 57 ]
python
en
['en', 'error', 'th']
False
M2MThroughTestCase.test_serialization
(self)
m2m-through models aren't serialized as m2m fields. Refs #8134
m2m-through models aren't serialized as m2m fields. Refs #8134
def test_serialization(self): "m2m-through models aren't serialized as m2m fields. Refs #8134" p = Person.objects.create(name="Bob") g = Group.objects.create(name="Roll") m = Membership.objects.create(person=p, group=g) pks = {"p_pk": p.pk, "g_pk": g.pk, "m_pk": m.pk} ...
[ "def", "test_serialization", "(", "self", ")", ":", "p", "=", "Person", ".", "objects", ".", "create", "(", "name", "=", "\"Bob\"", ")", "g", "=", "Group", ".", "objects", ".", "create", "(", "name", "=", "\"Roll\"", ")", "m", "=", "Membership", ".",...
[ 65, 4 ]
[ 96, 26 ]
python
en
['en', 'en', 'en']
True
M2MThroughTestCase.test_join_trimming
(self)
Check that we don't involve too many copies of the intermediate table when doing a join. Refs #8046, #8254
Check that we don't involve too many copies of the intermediate table when doing a join. Refs #8046, #8254
def test_join_trimming(self): "Check that we don't involve too many copies of the intermediate table when doing a join. Refs #8046, #8254" bob = Person.objects.create(name="Bob") jim = Person.objects.create(name="Jim") rock = Group.objects.create(name="Rock") roll = Group.object...
[ "def", "test_join_trimming", "(", "self", ")", ":", "bob", "=", "Person", ".", "objects", ".", "create", "(", "name", "=", "\"Bob\"", ")", "jim", "=", "Person", ".", "objects", ".", "create", "(", "name", "=", "\"Jim\"", ")", "rock", "=", "Group", "....
[ 98, 4 ]
[ 120, 9 ]
python
en
['en', 'en', 'en']
True
ThroughLoadDataTestCase.test_sequence_creation
(self)
Check that sequences on an m2m_through are created for the through model, not a phantom auto-generated m2m table. Refs #11107
Check that sequences on an m2m_through are created for the through model, not a phantom auto-generated m2m table. Refs #11107
def test_sequence_creation(self): "Check that sequences on an m2m_through are created for the through model, not a phantom auto-generated m2m table. Refs #11107" out = StringIO() management.call_command("dumpdata", "m2m_through_regress", format="json", stdout=out) self.assertJSONEqual(ou...
[ "def", "test_sequence_creation", "(", "self", ")", ":", "out", "=", "StringIO", "(", ")", "management", ".", "call_command", "(", "\"dumpdata\"", ",", "\"m2m_through_regress\"", ",", "format", "=", "\"json\"", ",", "stdout", "=", "out", ")", "self", ".", "as...
[ 231, 4 ]
[ 235, 336 ]
python
en
['en', 'en', 'en']
True
description_of
(lines, name='stdin')
Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str
Return a string describing the probable encoding of a file or list of strings.
def description_of(lines, name='stdin'): """ Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str """ u = Univers...
[ "def", "description_of", "(", "lines", ",", "name", "=", "'stdin'", ")", ":", "u", "=", "UniversalDetector", "(", ")", "for", "line", "in", "lines", ":", "line", "=", "bytearray", "(", "line", ")", "u", ".", "feed", "(", "line", ")", "# shortcut out of...
[ 25, 0 ]
[ 50, 44 ]
python
en
['en', 'error', 'th']
False
main
(argv=None)
Handles command line arguments and gets things started. :param argv: List of arguments, as if specified on the command-line. If None, ``sys.argv[1:]`` is used instead. :type argv: list of str
Handles command line arguments and gets things started.
def main(argv=None): """ Handles command line arguments and gets things started. :param argv: List of arguments, as if specified on the command-line. If None, ``sys.argv[1:]`` is used instead. :type argv: list of str """ # Get command line arguments parser = argparse.Argume...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "# Get command line arguments", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Takes one or more file paths and reports their detected \\\n encodings\"", ")", "parser", ".", ...
[ 53, 0 ]
[ 80, 40 ]
python
en
['en', 'error', 'th']
False
Collector.add
(self, objs, source=None, nullable=False, reverse_dependency=False)
Adds 'objs' to the collection of objects to be deleted. If the call is the result of a cascade, 'source' should be the model that caused it, and 'nullable' should be set to True if the relation can be null. Returns a list of all objects that were not already collected.
Adds 'objs' to the collection of objects to be deleted. If the call is the result of a cascade, 'source' should be the model that caused it, and 'nullable' should be set to True if the relation can be null.
def add(self, objs, source=None, nullable=False, reverse_dependency=False): """ Adds 'objs' to the collection of objects to be deleted. If the call is the result of a cascade, 'source' should be the model that caused it, and 'nullable' should be set to True if the relation can be null. ...
[ "def", "add", "(", "self", ",", "objs", ",", "source", "=", "None", ",", "nullable", "=", "False", ",", "reverse_dependency", "=", "False", ")", ":", "if", "not", "objs", ":", "return", "[", "]", "new_objs", "=", "[", "]", "model", "=", "objs", "["...
[ 70, 4 ]
[ 95, 23 ]
python
en
['en', 'error', 'th']
False
Collector.add_field_update
(self, field, value, objs)
Schedules a field update. 'objs' must be a homogeneous iterable collection of model instances (e.g. a QuerySet).
Schedules a field update. 'objs' must be a homogeneous iterable collection of model instances (e.g. a QuerySet).
def add_field_update(self, field, value, objs): """ Schedules a field update. 'objs' must be a homogeneous iterable collection of model instances (e.g. a QuerySet). """ if not objs: return model = objs[0].__class__ self.field_updates.setdefault( ...
[ "def", "add_field_update", "(", "self", ",", "field", ",", "value", ",", "objs", ")", ":", "if", "not", "objs", ":", "return", "model", "=", "objs", "[", "0", "]", ".", "__class__", "self", ".", "field_updates", ".", "setdefault", "(", "model", ",", ...
[ 97, 4 ]
[ 107, 47 ]
python
en
['en', 'error', 'th']
False
Collector.can_fast_delete
(self, objs, from_field=None)
Determines if the objects in the given queryset-like can be fast-deleted. This can be done if there are no cascades, no parents and no signal listeners for the object class. The 'from_field' tells where we are coming from - we need this to determine if the objects are in fact t...
Determines if the objects in the given queryset-like can be fast-deleted. This can be done if there are no cascades, no parents and no signal listeners for the object class.
def can_fast_delete(self, objs, from_field=None): """ Determines if the objects in the given queryset-like can be fast-deleted. This can be done if there are no cascades, no parents and no signal listeners for the object class. The 'from_field' tells where we are coming from - w...
[ "def", "can_fast_delete", "(", "self", ",", "objs", ",", "from_field", "=", "None", ")", ":", "if", "from_field", "and", "from_field", ".", "rel", ".", "on_delete", "is", "not", "CASCADE", ":", "return", "False", "if", "not", "(", "hasattr", "(", "objs",...
[ 109, 4 ]
[ 144, 19 ]
python
en
['en', 'error', 'th']
False
Collector.get_del_batches
(self, objs, field)
Returns the objs in suitably sized batches for the used connection.
Returns the objs in suitably sized batches for the used connection.
def get_del_batches(self, objs, field): """ Returns the objs in suitably sized batches for the used connection. """ conn_batch_size = max( connections[self.using].ops.bulk_batch_size([field.name], objs), 1) if len(objs) > conn_batch_size: return [objs[i:i ...
[ "def", "get_del_batches", "(", "self", ",", "objs", ",", "field", ")", ":", "conn_batch_size", "=", "max", "(", "connections", "[", "self", ".", "using", "]", ".", "ops", ".", "bulk_batch_size", "(", "[", "field", ".", "name", "]", ",", "objs", ")", ...
[ 146, 4 ]
[ 156, 25 ]
python
en
['en', 'error', 'th']
False
Collector.collect
(self, objs, source=None, nullable=False, collect_related=True, source_attr=None, reverse_dependency=False)
Adds 'objs' to the collection of objects to be deleted as well as all parent instances. 'objs' must be a homogeneous iterable collection of model instances (e.g. a QuerySet). If 'collect_related' is True, related objects will be handled by their respective on_delete handler. ...
Adds 'objs' to the collection of objects to be deleted as well as all parent instances. 'objs' must be a homogeneous iterable collection of model instances (e.g. a QuerySet). If 'collect_related' is True, related objects will be handled by their respective on_delete handler.
def collect(self, objs, source=None, nullable=False, collect_related=True, source_attr=None, reverse_dependency=False): """ Adds 'objs' to the collection of objects to be deleted as well as all parent instances. 'objs' must be a homogeneous iterable collection of model insta...
[ "def", "collect", "(", "self", ",", "objs", ",", "source", "=", "None", ",", "nullable", "=", "False", ",", "collect_related", "=", "True", ",", "source_attr", "=", "None", ",", "reverse_dependency", "=", "False", ")", ":", "if", "self", ".", "can_fast_d...
[ 158, 4 ]
[ 220, 47 ]
python
en
['en', 'error', 'th']
False
Collector.related_objects
(self, related, objs)
Gets a QuerySet of objects related to ``objs`` via the relation ``related``.
Gets a QuerySet of objects related to ``objs`` via the relation ``related``.
def related_objects(self, related, objs): """ Gets a QuerySet of objects related to ``objs`` via the relation ``related``. """ return related.model._base_manager.using(self.using).filter( **{"%s__in" % related.field.name: objs} )
[ "def", "related_objects", "(", "self", ",", "related", ",", "objs", ")", ":", "return", "related", ".", "model", ".", "_base_manager", ".", "using", "(", "self", ".", "using", ")", ".", "filter", "(", "*", "*", "{", "\"%s__in\"", "%", "related", ".", ...
[ 222, 4 ]
[ 229, 9 ]
python
en
['en', 'error', 'th']
False
ProjectState.clone
(self)
Returns an exact copy of this ProjectState
Returns an exact copy of this ProjectState
def clone(self): "Returns an exact copy of this ProjectState" return ProjectState( models=dict((k, v.clone()) for k, v in self.models.items()), real_apps=self.real_apps, )
[ "def", "clone", "(", "self", ")", ":", "return", "ProjectState", "(", "models", "=", "dict", "(", "(", "k", ",", "v", ".", "clone", "(", ")", ")", "for", "k", ",", "v", "in", "self", ".", "models", ".", "items", "(", ")", ")", ",", "real_apps",...
[ 34, 4 ]
[ 39, 9 ]
python
en
['en', 'en', 'en']
True
ProjectState.render
(self, include_real=None, ignore_swappable=False, skip_cache=False)
Turns the project state into actual models in a new Apps
Turns the project state into actual models in a new Apps
def render(self, include_real=None, ignore_swappable=False, skip_cache=False): "Turns the project state into actual models in a new Apps" if self.apps is None or skip_cache: # Any apps in self.real_apps should have all their models included # in the render. We don't use the origi...
[ "def", "render", "(", "self", ",", "include_real", "=", "None", ",", "ignore_swappable", "=", "False", ",", "skip_cache", "=", "False", ")", ":", "if", "self", ".", "apps", "is", "None", "or", "skip_cache", ":", "# Any apps in self.real_apps should have all thei...
[ 41, 4 ]
[ 96, 32 ]
python
en
['en', 'en', 'en']
True
ProjectState.from_apps
(cls, apps)
Takes in an Apps and returns a ProjectState matching it
Takes in an Apps and returns a ProjectState matching it
def from_apps(cls, apps): "Takes in an Apps and returns a ProjectState matching it" app_models = {} for model in apps.get_models(include_swapped=True): model_state = ModelState.from_model(model) app_models[(model_state.app_label, model_state.name.lower())] = model_state ...
[ "def", "from_apps", "(", "cls", ",", "apps", ")", ":", "app_models", "=", "{", "}", "for", "model", "in", "apps", ".", "get_models", "(", "include_swapped", "=", "True", ")", ":", "model_state", "=", "ModelState", ".", "from_model", "(", "model", ")", ...
[ 99, 4 ]
[ 105, 30 ]
python
en
['en', 'en', 'en']
True
ModelState.from_model
(cls, model, exclude_rels=False)
Feed me a model, get a ModelState representing it out.
Feed me a model, get a ModelState representing it out.
def from_model(cls, model, exclude_rels=False): """ Feed me a model, get a ModelState representing it out. """ # Deconstruct the fields fields = [] for field in model._meta.local_fields: if getattr(field, "rel", None) and exclude_rels: continue...
[ "def", "from_model", "(", "cls", ",", "model", ",", "exclude_rels", "=", "False", ")", ":", "# Deconstruct the fields", "fields", "=", "[", "]", "for", "field", "in", "model", ".", "_meta", ".", "local_fields", ":", "if", "getattr", "(", "field", ",", "\...
[ 164, 4 ]
[ 256, 9 ]
python
en
['en', 'error', 'th']
False
ModelState.construct_fields
(self)
Deep-clone the fields using deconstruction
Deep-clone the fields using deconstruction
def construct_fields(self): "Deep-clone the fields using deconstruction" for name, field in self.fields: _, path, args, kwargs = field.deconstruct() field_class = import_string(path) yield name, field_class(*args, **kwargs)
[ "def", "construct_fields", "(", "self", ")", ":", "for", "name", ",", "field", "in", "self", ".", "fields", ":", "_", ",", "path", ",", "args", ",", "kwargs", "=", "field", ".", "deconstruct", "(", ")", "field_class", "=", "import_string", "(", "path",...
[ 275, 4 ]
[ 280, 52 ]
python
en
['en', 'lb', 'en']
True
ModelState.clone
(self)
Returns an exact copy of this ModelState
Returns an exact copy of this ModelState
def clone(self): "Returns an exact copy of this ModelState" return self.__class__( app_label=self.app_label, name=self.name, fields=list(self.construct_fields()), options=dict(self.options), bases=self.bases, )
[ "def", "clone", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "app_label", "=", "self", ".", "app_label", ",", "name", "=", "self", ".", "name", ",", "fields", "=", "list", "(", "self", ".", "construct_fields", "(", ")", ")", ",", ...
[ 282, 4 ]
[ 290, 9 ]
python
en
['en', 'en', 'en']
True
ModelState.render
(self, apps)
Creates a Model object from our current state into the given apps
Creates a Model object from our current state into the given apps
def render(self, apps): "Creates a Model object from our current state into the given apps" # First, make a Meta object meta_contents = {'app_label': self.app_label, "apps": apps} meta_contents.update(self.options) meta = type(str("Meta"), tuple(), meta_contents) # Then, ...
[ "def", "render", "(", "self", ",", "apps", ")", ":", "# First, make a Meta object", "meta_contents", "=", "{", "'app_label'", ":", "self", ".", "app_label", ",", "\"apps\"", ":", "apps", "}", "meta_contents", ".", "update", "(", "self", ".", "options", ")", ...
[ 292, 4 ]
[ 315, 9 ]
python
en
['en', 'en', 'en']
True
BaseSpatialOperations.geo_db_type
(self, f)
Returns the database column type for the geometry field on the spatial backend.
Returns the database column type for the geometry field on the spatial backend.
def geo_db_type(self, f): """ Returns the database column type for the geometry field on the spatial backend. """ raise NotImplementedError('subclasses of BaseSpatialOperations must provide a geo_db_type() method')
[ "def", "geo_db_type", "(", "self", ",", "f", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseSpatialOperations must provide a geo_db_type() method'", ")" ]
[ 174, 4 ]
[ 179, 108 ]
python
en
['en', 'error', 'th']
False
BaseSpatialOperations.get_distance
(self, f, value, lookup_type)
Returns the distance parameters for the given geometry field, lookup value, and lookup type.
Returns the distance parameters for the given geometry field, lookup value, and lookup type.
def get_distance(self, f, value, lookup_type): """ Returns the distance parameters for the given geometry field, lookup value, and lookup type. """ raise NotImplementedError('Distance operations not available on this spatial backend.')
[ "def", "get_distance", "(", "self", ",", "f", ",", "value", ",", "lookup_type", ")", ":", "raise", "NotImplementedError", "(", "'Distance operations not available on this spatial backend.'", ")" ]
[ 181, 4 ]
[ 186, 95 ]
python
en
['en', 'error', 'th']
False
BaseSpatialOperations.get_geom_placeholder
(self, f, value)
Returns the placeholder for the given geometry field with the given value. Depending on the spatial backend, the placeholder may contain a stored procedure call to the transformation function of the spatial backend.
Returns the placeholder for the given geometry field with the given value. Depending on the spatial backend, the placeholder may contain a stored procedure call to the transformation function of the spatial backend.
def get_geom_placeholder(self, f, value): """ Returns the placeholder for the given geometry field with the given value. Depending on the spatial backend, the placeholder may contain a stored procedure call to the transformation function of the spatial backend. """ ...
[ "def", "get_geom_placeholder", "(", "self", ",", "f", ",", "value", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BaseSpatialOperations must provide a geo_db_placeholder() method'", ")" ]
[ 188, 4 ]
[ 195, 115 ]
python
en
['en', 'error', 'th']
False
BaseSpatialOperations.get_expression_column
(self, evaluator)
Helper method to return the quoted column string from the evaluator for its expression.
Helper method to return the quoted column string from the evaluator for its expression.
def get_expression_column(self, evaluator): """ Helper method to return the quoted column string from the evaluator for its expression. """ for expr, col_tup in evaluator.cols: if expr is evaluator.expression: return '%s.%s' % tuple(map(self.quote_name...
[ "def", "get_expression_column", "(", "self", ",", "evaluator", ")", ":", "for", "expr", ",", "col_tup", "in", "evaluator", ".", "cols", ":", "if", "expr", "is", "evaluator", ".", "expression", ":", "return", "'%s.%s'", "%", "tuple", "(", "map", "(", "sel...
[ 197, 4 ]
[ 205, 72 ]
python
en
['en', 'error', 'th']
False
load_handler
(path, *args, **kwargs)
Given a path to a handler, return an instance of that handler. E.g.:: >>> from django.http import HttpRequest >>> request = HttpRequest() >>> load_handler('django.core.files.uploadhandler.TemporaryFileUploadHandler', request) <TemporaryFileUploadHandler object at 0x...>
Given a path to a handler, return an instance of that handler.
def load_handler(path, *args, **kwargs): """ Given a path to a handler, return an instance of that handler. E.g.:: >>> from django.http import HttpRequest >>> request = HttpRequest() >>> load_handler('django.core.files.uploadhandler.TemporaryFileUploadHandler', request) <Tem...
[ "def", "load_handler", "(", "path", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "import_string", "(", "path", ")", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 205, 0 ]
[ 216, 47 ]
python
en
['en', 'error', 'th']
False
FileUploadHandler.handle_raw_input
(self, input_data, META, content_length, boundary, encoding=None)
Handle the raw input from the client. Parameters: :input_data: An object that supports reading via .read(). :META: ``request.META``. :content_length: The (integer) value of the Content-Length header from the ...
Handle the raw input from the client.
def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None): """ Handle the raw input from the client. Parameters: :input_data: An object that supports reading via .read(). :META: ``request.META``. :c...
[ "def", "handle_raw_input", "(", "self", ",", "input_data", ",", "META", ",", "content_length", ",", "boundary", ",", "encoding", "=", "None", ")", ":", "pass" ]
[ 76, 4 ]
[ 92, 12 ]
python
en
['en', 'error', 'th']
False
FileUploadHandler.new_file
(self, field_name, file_name, content_type, content_length, charset=None, content_type_extra=None)
Signal that a new file has been started. Warning: As with any data from the client, you should not trust content_length (and sometimes won't even get it).
Signal that a new file has been started.
def new_file(self, field_name, file_name, content_type, content_length, charset=None, content_type_extra=None): """ Signal that a new file has been started. Warning: As with any data from the client, you should not trust content_length (and sometimes won't even get it). """ ...
[ "def", "new_file", "(", "self", ",", "field_name", ",", "file_name", ",", "content_type", ",", "content_length", ",", "charset", "=", "None", ",", "content_type_extra", "=", "None", ")", ":", "self", ".", "field_name", "=", "field_name", "self", ".", "file_n...
[ 94, 4 ]
[ 106, 52 ]
python
en
['en', 'error', 'th']
False
FileUploadHandler.receive_data_chunk
(self, raw_data, start)
Receive data from the streamed upload parser. ``start`` is the position in the file of the chunk.
Receive data from the streamed upload parser. ``start`` is the position in the file of the chunk.
def receive_data_chunk(self, raw_data, start): """ Receive data from the streamed upload parser. ``start`` is the position in the file of the chunk. """ raise NotImplementedError('subclasses of FileUploadHandler must provide a receive_data_chunk() method')
[ "def", "receive_data_chunk", "(", "self", ",", "raw_data", ",", "start", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of FileUploadHandler must provide a receive_data_chunk() method'", ")" ]
[ 108, 4 ]
[ 113, 111 ]
python
en
['en', 'error', 'th']
False
FileUploadHandler.file_complete
(self, file_size)
Signal that a file has completed. File size corresponds to the actual size accumulated by all the chunks. Subclasses should return a valid ``UploadedFile`` object.
Signal that a file has completed. File size corresponds to the actual size accumulated by all the chunks.
def file_complete(self, file_size): """ Signal that a file has completed. File size corresponds to the actual size accumulated by all the chunks. Subclasses should return a valid ``UploadedFile`` object. """ raise NotImplementedError('subclasses of FileUploadHandler must...
[ "def", "file_complete", "(", "self", ",", "file_size", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of FileUploadHandler must provide a file_complete() method'", ")" ]
[ 115, 4 ]
[ 122, 106 ]
python
en
['en', 'error', 'th']
False
FileUploadHandler.upload_complete
(self)
Signal that the upload is complete. Subclasses should perform cleanup that is necessary for this handler.
Signal that the upload is complete. Subclasses should perform cleanup that is necessary for this handler.
def upload_complete(self): """ Signal that the upload is complete. Subclasses should perform cleanup that is necessary for this handler. """ pass
[ "def", "upload_complete", "(", "self", ")", ":", "pass" ]
[ 124, 4 ]
[ 129, 12 ]
python
en
['en', 'error', 'th']
False
TemporaryFileUploadHandler.new_file
(self, file_name, *args, **kwargs)
Create the file object to append to as data is coming in.
Create the file object to append to as data is coming in.
def new_file(self, file_name, *args, **kwargs): """ Create the file object to append to as data is coming in. """ super(TemporaryFileUploadHandler, self).new_file(file_name, *args, **kwargs) self.file = TemporaryUploadedFile(self.file_name, self.content_type, 0, self.charset, sel...
[ "def", "new_file", "(", "self", ",", "file_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "TemporaryFileUploadHandler", ",", "self", ")", ".", "new_file", "(", "file_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", "s...
[ 139, 4 ]
[ 144, 118 ]
python
en
['en', 'error', 'th']
False
MemoryFileUploadHandler.handle_raw_input
(self, input_data, META, content_length, boundary, encoding=None)
Use the content_length to signal whether or not this handler should be in use.
Use the content_length to signal whether or not this handler should be in use.
def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None): """ Use the content_length to signal whether or not this handler should be in use. """ # Check the content-length header to see if we should # If the post is too large, we cannot use the Memory...
[ "def", "handle_raw_input", "(", "self", ",", "input_data", ",", "META", ",", "content_length", ",", "boundary", ",", "encoding", "=", "None", ")", ":", "# Check the content-length header to see if we should", "# If the post is too large, we cannot use the Memory handler.", "i...
[ 160, 4 ]
[ 169, 33 ]
python
en
['en', 'error', 'th']
False
MemoryFileUploadHandler.receive_data_chunk
(self, raw_data, start)
Add the data to the BytesIO file.
Add the data to the BytesIO file.
def receive_data_chunk(self, raw_data, start): """ Add the data to the BytesIO file. """ if self.activated: self.file.write(raw_data) else: return raw_data
[ "def", "receive_data_chunk", "(", "self", ",", "raw_data", ",", "start", ")", ":", "if", "self", ".", "activated", ":", "self", ".", "file", ".", "write", "(", "raw_data", ")", "else", ":", "return", "raw_data" ]
[ 177, 4 ]
[ 184, 27 ]
python
en
['en', 'error', 'th']
False
MemoryFileUploadHandler.file_complete
(self, file_size)
Return a file object if we're activated.
Return a file object if we're activated.
def file_complete(self, file_size): """ Return a file object if we're activated. """ if not self.activated: return self.file.seek(0) return InMemoryUploadedFile( file=self.file, field_name=self.field_name, name=self.file_na...
[ "def", "file_complete", "(", "self", ",", "file_size", ")", ":", "if", "not", "self", ".", "activated", ":", "return", "self", ".", "file", ".", "seek", "(", "0", ")", "return", "InMemoryUploadedFile", "(", "file", "=", "self", ".", "file", ",", "field...
[ 186, 4 ]
[ 202, 9 ]
python
en
['en', 'error', 'th']
False
CommonMiddleware.process_request
(self, request)
Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW
Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW
def process_request(self, request): """ Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW """ # Check for denied User-Agents if 'HTTP_USER_AGENT' in request.META: for user_agent_regex in settings.DISALLOW...
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "# Check for denied User-Agents", "if", "'HTTP_USER_AGENT'", "in", "request", ".", "META", ":", "for", "user_agent_regex", "in", "settings", ".", "DISALLOWED_USER_AGENTS", ":", "if", "user_agent_regex", ...
[ 37, 4 ]
[ 102, 57 ]
python
en
['en', 'error', 'th']
False
CommonMiddleware.process_response
(self, request, response)
Calculate the ETag, if needed.
Calculate the ETag, if needed.
def process_response(self, request, response): """ Calculate the ETag, if needed. """ if settings.USE_ETAGS: if response.has_header('ETag'): etag = response['ETag'] elif response.streaming: etag = None else: ...
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "if", "settings", ".", "USE_ETAGS", ":", "if", "response", ".", "has_header", "(", "'ETag'", ")", ":", "etag", "=", "response", "[", "'ETag'", "]", "elif", "response", "."...
[ 104, 4 ]
[ 124, 23 ]
python
en
['en', 'error', 'th']
False
BrokenLinkEmailsMiddleware.process_response
(self, request, response)
Send broken link emails for relevant 404 NOT FOUND responses.
Send broken link emails for relevant 404 NOT FOUND responses.
def process_response(self, request, response): """ Send broken link emails for relevant 404 NOT FOUND responses. """ if response.status_code == 404 and not settings.DEBUG: domain = request.get_host() path = request.get_full_path() referer = force_text(...
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "if", "response", ".", "status_code", "==", "404", "and", "not", "settings", ".", "DEBUG", ":", "domain", "=", "request", ".", "get_host", "(", ")", "path", "=", "request"...
[ 129, 4 ]
[ 149, 23 ]
python
en
['en', 'error', 'th']
False
BrokenLinkEmailsMiddleware.is_internal_request
(self, domain, referer)
Returns True if the referring URL is the same domain as the current request.
Returns True if the referring URL is the same domain as the current request.
def is_internal_request(self, domain, referer): """ Returns True if the referring URL is the same domain as the current request. """ # Different subdomains are treated as different domains. return bool(re.match("^https?://%s/" % re.escape(domain), referer))
[ "def", "is_internal_request", "(", "self", ",", "domain", ",", "referer", ")", ":", "# Different subdomains are treated as different domains.", "return", "bool", "(", "re", ".", "match", "(", "\"^https?://%s/\"", "%", "re", ".", "escape", "(", "domain", ")", ",", ...
[ 151, 4 ]
[ 156, 75 ]
python
en
['en', 'error', 'th']
False
BrokenLinkEmailsMiddleware.is_ignorable_request
(self, request, uri, domain, referer)
Returns True if the given request *shouldn't* notify the site managers.
Returns True if the given request *shouldn't* notify the site managers.
def is_ignorable_request(self, request, uri, domain, referer): """ Returns True if the given request *shouldn't* notify the site managers. """ # '?' in referer is identified as search engine source if (not referer or (not self.is_internal_request(domain, referer) ...
[ "def", "is_ignorable_request", "(", "self", ",", "request", ",", "uri", ",", "domain", ",", "referer", ")", ":", "# '?' in referer is identified as search engine source", "if", "(", "not", "referer", "or", "(", "not", "self", ".", "is_internal_request", "(", "doma...
[ 158, 4 ]
[ 166, 82 ]
python
en
['en', 'error', 'th']
False
PaymentsConfig.ready
(self)
Verify active payment provider configuration
Verify active payment provider configuration
def ready(self): """Verify active payment provider configuration""" if settings.RESPA_PAYMENTS_ENABLED: from .providers import load_provider_config load_provider_config()
[ "def", "ready", "(", "self", ")", ":", "if", "settings", ".", "RESPA_PAYMENTS_ENABLED", ":", "from", ".", "providers", "import", "load_provider_config", "load_provider_config", "(", ")" ]
[ 7, 4 ]
[ 11, 34 ]
python
en
['en', 'fr', 'en']
True
Paginator.validate_number
(self, number)
Validates the given 1-based page number.
Validates the given 1-based page number.
def validate_number(self, number): """ Validates the given 1-based page number. """ try: number = int(number) except (TypeError, ValueError): raise PageNotAnInteger('That page number is not an integer') if number < 1: raise EmptyPage('T...
[ "def", "validate_number", "(", "self", ",", "number", ")", ":", "try", ":", "number", "=", "int", "(", "number", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "PageNotAnInteger", "(", "'That page number is not an integer'", ")", "if", ...
[ 28, 4 ]
[ 43, 21 ]
python
en
['en', 'error', 'th']
False
Paginator.page
(self, number)
Returns a Page object for the given 1-based page number.
Returns a Page object for the given 1-based page number.
def page(self, number): """ Returns a Page object for the given 1-based page number. """ number = self.validate_number(number) bottom = (number - 1) * self.per_page top = bottom + self.per_page if top + self.orphans >= self.count: top = self.count ...
[ "def", "page", "(", "self", ",", "number", ")", ":", "number", "=", "self", ".", "validate_number", "(", "number", ")", "bottom", "=", "(", "number", "-", "1", ")", "*", "self", ".", "per_page", "top", "=", "bottom", "+", "self", ".", "per_page", "...
[ 45, 4 ]
[ 54, 73 ]
python
en
['en', 'error', 'th']
False
Paginator._get_page
(self, *args, **kwargs)
Returns an instance of a single page. This hook can be used by subclasses to use an alternative to the standard :cls:`Page` object.
Returns an instance of a single page.
def _get_page(self, *args, **kwargs): """ Returns an instance of a single page. This hook can be used by subclasses to use an alternative to the standard :cls:`Page` object. """ return Page(*args, **kwargs)
[ "def", "_get_page", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "Page", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 56, 4 ]
[ 63, 36 ]
python
en
['en', 'error', 'th']
False
Paginator._get_count
(self)
Returns the total number of objects, across all pages.
Returns the total number of objects, across all pages.
def _get_count(self): """ Returns the total number of objects, across all pages. """ if self._count is None: try: self._count = self.object_list.count() except (AttributeError, TypeError): # AttributeError if object_list has no coun...
[ "def", "_get_count", "(", "self", ")", ":", "if", "self", ".", "_count", "is", "None", ":", "try", ":", "self", ".", "_count", "=", "self", ".", "object_list", ".", "count", "(", ")", "except", "(", "AttributeError", ",", "TypeError", ")", ":", "# At...
[ 65, 4 ]
[ 77, 26 ]
python
en
['en', 'error', 'th']
False
Paginator._get_num_pages
(self)
Returns the total number of pages.
Returns the total number of pages.
def _get_num_pages(self): """ Returns the total number of pages. """ if self._num_pages is None: if self.count == 0 and not self.allow_empty_first_page: self._num_pages = 0 else: hits = max(1, self.count - self.orphans) ...
[ "def", "_get_num_pages", "(", "self", ")", ":", "if", "self", ".", "_num_pages", "is", "None", ":", "if", "self", ".", "count", "==", "0", "and", "not", "self", ".", "allow_empty_first_page", ":", "self", ".", "_num_pages", "=", "0", "else", ":", "hits...
[ 80, 4 ]
[ 90, 30 ]
python
en
['en', 'error', 'th']
False
Paginator._get_page_range
(self)
Returns a 1-based range of pages for iterating through within a template for loop.
Returns a 1-based range of pages for iterating through within a template for loop.
def _get_page_range(self): """ Returns a 1-based range of pages for iterating through within a template for loop. """ return list(six.moves.range(1, self.num_pages + 1))
[ "def", "_get_page_range", "(", "self", ")", ":", "return", "list", "(", "six", ".", "moves", ".", "range", "(", "1", ",", "self", ".", "num_pages", "+", "1", ")", ")" ]
[ 93, 4 ]
[ 98, 59 ]
python
en
['en', 'error', 'th']
False
Page.start_index
(self)
Returns the 1-based index of the first object on this page, relative to total objects in the paginator.
Returns the 1-based index of the first object on this page, relative to total objects in the paginator.
def start_index(self): """ Returns the 1-based index of the first object on this page, relative to total objects in the paginator. """ # Special case, return zero if no items. if self.paginator.count == 0: return 0 return (self.paginator.per_page * (se...
[ "def", "start_index", "(", "self", ")", ":", "# Special case, return zero if no items.", "if", "self", ".", "paginator", ".", "count", "==", "0", ":", "return", "0", "return", "(", "self", ".", "paginator", ".", "per_page", "*", "(", "self", ".", "number", ...
[ 142, 4 ]
[ 150, 64 ]
python
en
['en', 'error', 'th']
False
Page.end_index
(self)
Returns the 1-based index of the last object on this page, relative to total objects found (hits).
Returns the 1-based index of the last object on this page, relative to total objects found (hits).
def end_index(self): """ Returns the 1-based index of the last object on this page, relative to total objects found (hits). """ # Special case for the last page because there can be orphans. if self.number == self.paginator.num_pages: return self.paginator.cou...
[ "def", "end_index", "(", "self", ")", ":", "# Special case for the last page because there can be orphans.", "if", "self", ".", "number", "==", "self", ".", "paginator", ".", "num_pages", ":", "return", "self", ".", "paginator", ".", "count", "return", "self", "."...
[ 152, 4 ]
[ 160, 52 ]
python
en
['en', 'error', 'th']
False
one_time
(method: Callable[[], ReturnT])
Use this decorator with extreme caution. The function you wrap should have no dependency on any arguments (no args, no kwargs) nor should it depend on any global state.
Use this decorator with extreme caution. The function you wrap should have no dependency on any arguments (no args, no kwargs) nor should it depend on any global state.
def one_time(method: Callable[[], ReturnT]) -> Callable[[], ReturnT]: """ Use this decorator with extreme caution. The function you wrap should have no dependency on any arguments (no args, no kwargs) nor should it depend on any global state. """ val = None def cache_wrapper() -> Return...
[ "def", "one_time", "(", "method", ":", "Callable", "[", "[", "]", ",", "ReturnT", "]", ")", "->", "Callable", "[", "[", "]", ",", "ReturnT", "]", ":", "val", "=", "None", "def", "cache_wrapper", "(", ")", "->", "ReturnT", ":", "nonlocal", "val", "i...
[ 83, 0 ]
[ 98, 24 ]
python
en
['en', 'error', 'th']
False
rewrite_local_links_to_relative
(db_data: Optional[DbData], link: str)
If the link points to a local destination (e.g. #narrow/...), generate a relative link that will open it in the current window.
If the link points to a local destination (e.g. #narrow/...), generate a relative link that will open it in the current window.
def rewrite_local_links_to_relative(db_data: Optional[DbData], link: str) -> str: """If the link points to a local destination (e.g. #narrow/...), generate a relative link that will open it in the current window. """ if db_data: realm_uri_prefix = db_data["realm_uri"] + "/" if ( ...
[ "def", "rewrite_local_links_to_relative", "(", "db_data", ":", "Optional", "[", "DbData", "]", ",", "link", ":", "str", ")", "->", "str", ":", "if", "db_data", ":", "realm_uri_prefix", "=", "db_data", "[", "\"realm_uri\"", "]", "+", "\"/\"", "if", "(", "li...
[ 258, 0 ]
[ 271, 15 ]
python
en
['en', 'en', 'en']
True
sanitize_url
(url: str)
Sanitize a URL against XSS attacks. See the docstring on markdown.inlinepatterns.LinkPattern.sanitize_url.
Sanitize a URL against XSS attacks. See the docstring on markdown.inlinepatterns.LinkPattern.sanitize_url.
def sanitize_url(url: str) -> Optional[str]: """ Sanitize a URL against XSS attacks. See the docstring on markdown.inlinepatterns.LinkPattern.sanitize_url. """ try: parts = urllib.parse.urlparse(url.replace(" ", "%20")) scheme, netloc, path, params, query, fragment = parts except...
[ "def", "sanitize_url", "(", "url", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "try", ":", "parts", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ".", "replace", "(", "\" \"", ",", "\"%20\"", ")", ")", "scheme", ",", "netlo...
[ 1544, 0 ]
[ 1596, 83 ]
python
en
['en', 'error', 'th']
False
prepare_linkifier_pattern
(source: str)
Augment a linkifier so it only matches after start-of-string, whitespace, or opening delimiters, won't match if there are word characters directly after, and saves what was matched as OUTER_CAPTURE_GROUP.
Augment a linkifier so it only matches after start-of-string, whitespace, or opening delimiters, won't match if there are word characters directly after, and saves what was matched as OUTER_CAPTURE_GROUP.
def prepare_linkifier_pattern(source: str) -> str: """Augment a linkifier so it only matches after start-of-string, whitespace, or opening delimiters, won't match if there are word characters directly after, and saves what was matched as OUTER_CAPTURE_GROUP.""" return fr"""(?<![^\s'"\(,:<])(?P<{OUTE...
[ "def", "prepare_linkifier_pattern", "(", "source", ":", "str", ")", "->", "str", ":", "return", "fr\"\"\"(?<![^\\s'\"\\(,:<])(?P<{OUTER_CAPTURE_GROUP}>{source})(?!\\w)\"\"\"" ]
[ 1783, 0 ]
[ 1788, 77 ]
python
en
['en', 'en', 'en']
True
InlineInterestingLinkProcessor.twitter_text
( self, text: str, urls: List[Dict[str, str]], user_mentions: List[Dict[str, Any]], media: List[Dict[str, Any]], )
Use data from the Twitter API to turn links, mentions and media into A tags. Also convert Unicode emojis to images. This works by using the URLs, user_mentions and media data from the twitter API and searching for Unicode emojis in the text using `unicode_emoji_regex`. ...
Use data from the Twitter API to turn links, mentions and media into A tags. Also convert Unicode emojis to images.
def twitter_text( self, text: str, urls: List[Dict[str, str]], user_mentions: List[Dict[str, Any]], media: List[Dict[str, Any]], ) -> Element: """ Use data from the Twitter API to turn links, mentions and media into A tags. Also convert Unicode emojis ...
[ "def", "twitter_text", "(", "self", ",", "text", ":", "str", ",", "urls", ":", "List", "[", "Dict", "[", "str", ",", "str", "]", "]", ",", "user_mentions", ":", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ",", "media", ":", "List", "...
[ 892, 4 ]
[ 1011, 16 ]
python
en
['en', 'error', 'th']
False
MarkdownListPreprocessor.run
(self, lines: List[str])
Insert a newline between a paragraph and ulist if missing
Insert a newline between a paragraph and ulist if missing
def run(self, lines: List[str]) -> List[str]: """ Insert a newline between a paragraph and ulist if missing """ inserts = 0 in_code_fence: bool = False open_fences: List[Fence] = [] copy = lines[:] for i in range(len(lines) - 1): # Ignore anything that is insi...
[ "def", "run", "(", "self", ",", "lines", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "inserts", "=", "0", "in_code_fence", ":", "bool", "=", "False", "open_fences", ":", "List", "[", "Fence", "]", "=", "[", "]", "copy",...
[ 1737, 4 ]
[ 1774, 19 ]
python
en
['en', 'en', 'en']
True
MentionData.get_user_ids
(self)
Returns the user IDs that might have been mentioned by this content. Note that because this data structure has not parsed the message and does not know about escaping/code blocks, this will overestimate the list of user ids.
Returns the user IDs that might have been mentioned by this content. Note that because this data structure has not parsed the message and does not know about escaping/code blocks, this will overestimate the list of user ids.
def get_user_ids(self) -> Set[int]: """ Returns the user IDs that might have been mentioned by this content. Note that because this data structure has not parsed the message and does not know about escaping/code blocks, this will overestimate the list of user ids. """ ...
[ "def", "get_user_ids", "(", "self", ")", "->", "Set", "[", "int", "]", ":", "return", "set", "(", "self", ".", "user_id_info", ".", "keys", "(", ")", ")" ]
[ 2494, 4 ]
[ 2501, 44 ]
python
en
['en', 'error', 'th']
False
Unit.get_opening_hours
(self, begin=None, end=None)
:rtype : dict[str, list[dict[str, datetime.datetime]]] :type begin: datetime.date :type end: datetime.date
:rtype : dict[str, list[dict[str, datetime.datetime]]] :type begin: datetime.date :type end: datetime.date
def get_opening_hours(self, begin=None, end=None): """ :rtype : dict[str, list[dict[str, datetime.datetime]]] :type begin: datetime.date :type end: datetime.date """ return get_opening_hours(self.time_zone, list(self.periods.all()), begin, end)
[ "def", "get_opening_hours", "(", "self", ",", "begin", "=", "None", ",", "end", "=", "None", ")", ":", "return", "get_opening_hours", "(", "self", ".", "time_zone", ",", "list", "(", "self", ".", "periods", ".", "all", "(", ")", ")", ",", "begin", ",...
[ 124, 4 ]
[ 130, 86 ]
python
en
['en', 'error', 'th']
False
Unit.is_editable
(self)
Whether unit is editable by normal admin users or not
Whether unit is editable by normal admin users or not
def is_editable(self): """ Whether unit is editable by normal admin users or not """ return not (self.has_imported_data() or self.has_imported_hours())
[ "def", "is_editable", "(", "self", ")", ":", "return", "not", "(", "self", ".", "has_imported_data", "(", ")", "or", "self", ".", "has_imported_hours", "(", ")", ")" ]
[ 162, 4 ]
[ 164, 74 ]
python
en
['en', 'en', 'en']
True
Choices.__str__
(self)
Use value when cast to str, so that Choices set as model instance attributes are rendered as expected in templates and similar contexts.
Use value when cast to str, so that Choices set as model instance attributes are rendered as expected in templates and similar contexts.
def __str__(self): """ Use value when cast to str, so that Choices set as model instance attributes are rendered as expected in templates and similar contexts. """ return str(self.value)
[ "def", "__str__", "(", "self", ")", ":", "return", "str", "(", "self", ".", "value", ")" ]
[ 64, 4 ]
[ 69, 30 ]
python
en
['en', 'error', 'th']
False
SessionBase.encode
(self, session_dict)
Returns the given session dictionary serialized and encoded as a string.
Returns the given session dictionary serialized and encoded as a string.
def encode(self, session_dict): "Returns the given session dictionary serialized and encoded as a string." serialized = self.serializer().dumps(session_dict) hash = self._hash(serialized) return base64.b64encode(hash.encode() + b":" + serialized).decode('ascii')
[ "def", "encode", "(", "self", ",", "session_dict", ")", ":", "serialized", "=", "self", ".", "serializer", "(", ")", ".", "dumps", "(", "session_dict", ")", "hash", "=", "self", ".", "_hash", "(", "serialized", ")", "return", "base64", ".", "b64encode", ...
[ 86, 4 ]
[ 90, 82 ]
python
en
['en', 'en', 'en']
True
SessionBase.is_empty
(self)
Returns True when there is no session_key and the session is empty
Returns True when there is no session_key and the session is empty
def is_empty(self): "Returns True when there is no session_key and the session is empty" try: return not bool(self._session_key) and not self._session_cache except AttributeError: return True
[ "def", "is_empty", "(", "self", ")", ":", "try", ":", "return", "not", "bool", "(", "self", ".", "_session_key", ")", "and", "not", "self", ".", "_session_cache", "except", "AttributeError", ":", "return", "True" ]
[ 144, 4 ]
[ 149, 23 ]
python
en
['en', 'en', 'en']
True
SessionBase._get_new_session_key
(self)
Returns session key that isn't being used.
Returns session key that isn't being used.
def _get_new_session_key(self): "Returns session key that isn't being used." while True: session_key = get_random_string(32, VALID_KEY_CHARS) if not self.exists(session_key): break return session_key
[ "def", "_get_new_session_key", "(", "self", ")", ":", "while", "True", ":", "session_key", "=", "get_random_string", "(", "32", ",", "VALID_KEY_CHARS", ")", "if", "not", "self", ".", "exists", "(", "session_key", ")", ":", "break", "return", "session_key" ]
[ 151, 4 ]
[ 157, 26 ]
python
en
['en', 'en', 'en']
True
SessionBase._get_session
(self, no_load=False)
Lazily loads session from storage (unless "no_load" is True, when only an empty dict is stored) and stores it in the current instance.
Lazily loads session from storage (unless "no_load" is True, when only an empty dict is stored) and stores it in the current instance.
def _get_session(self, no_load=False): """ Lazily loads session from storage (unless "no_load" is True, when only an empty dict is stored) and stores it in the current instance. """ self.accessed = True try: return self._session_cache except AttributeE...
[ "def", "_get_session", "(", "self", ",", "no_load", "=", "False", ")", ":", "self", ".", "accessed", "=", "True", "try", ":", "return", "self", ".", "_session_cache", "except", "AttributeError", ":", "if", "self", ".", "session_key", "is", "None", "or", ...
[ 169, 4 ]
[ 182, 34 ]
python
en
['en', 'error', 'th']
False
SessionBase.get_expiry_age
(self, **kwargs)
Get the number of seconds until the session expires. Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session.
Get the number of seconds until the session expires.
def get_expiry_age(self, **kwargs): """Get the number of seconds until the session expires. Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session. """ try: modification = kwargs['modifica...
[ "def", "get_expiry_age", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "modification", "=", "kwargs", "[", "'modification'", "]", "except", "KeyError", ":", "modification", "=", "timezone", ".", "now", "(", ")", "# Make the difference between \"e...
[ 186, 4 ]
[ 209, 49 ]
python
en
['en', 'en', 'en']
True
SessionBase.get_expiry_date
(self, **kwargs)
Get session the expiry date (as a datetime object). Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session.
Get session the expiry date (as a datetime object).
def get_expiry_date(self, **kwargs): """Get session the expiry date (as a datetime object). Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session. """ try: modification = kwargs['modifica...
[ "def", "get_expiry_date", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "modification", "=", "kwargs", "[", "'modification'", "]", "except", "KeyError", ":", "modification", "=", "timezone", ".", "now", "(", ")", "# Same comment as in get_expiry_...
[ 211, 4 ]
[ 231, 55 ]
python
en
['en', 'en', 'en']
True
SessionBase.set_expiry
(self, value)
Sets a custom expiration for the session. ``value`` can be an integer, a Python ``datetime`` or ``timedelta`` object or ``None``. If ``value`` is an integer, the session will expire after that many seconds of inactivity. If set to ``0`` then the session will expire on browser c...
Sets a custom expiration for the session. ``value`` can be an integer, a Python ``datetime`` or ``timedelta`` object or ``None``.
def set_expiry(self, value): """ Sets a custom expiration for the session. ``value`` can be an integer, a Python ``datetime`` or ``timedelta`` object or ``None``. If ``value`` is an integer, the session will expire after that many seconds of inactivity. If set to ``0`` then the ...
[ "def", "set_expiry", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "# Remove any custom expiration for this session.", "try", ":", "del", "self", "[", "'_session_expiry'", "]", "except", "KeyError", ":", "pass", "return", "if", "isinstan...
[ 233, 4 ]
[ 257, 39 ]
python
en
['en', 'error', 'th']
False
SessionBase.get_expire_at_browser_close
(self)
Returns ``True`` if the session is set to expire when the browser closes, and ``False`` if there's an expiry date. Use ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry date/age, if there is one.
Returns ``True`` if the session is set to expire when the browser closes, and ``False`` if there's an expiry date. Use ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry date/age, if there is one.
def get_expire_at_browser_close(self): """ Returns ``True`` if the session is set to expire when the browser closes, and ``False`` if there's an expiry date. Use ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry date/age, if there is one. """ ...
[ "def", "get_expire_at_browser_close", "(", "self", ")", ":", "if", "self", ".", "get", "(", "'_session_expiry'", ")", "is", "None", ":", "return", "settings", ".", "SESSION_EXPIRE_AT_BROWSER_CLOSE", "return", "self", ".", "get", "(", "'_session_expiry'", ")", "=...
[ 259, 4 ]
[ 268, 47 ]
python
en
['en', 'error', 'th']
False
SessionBase.flush
(self)
Removes the current session data from the database and regenerates the key.
Removes the current session data from the database and regenerates the key.
def flush(self): """ Removes the current session data from the database and regenerates the key. """ self.clear() self.delete() self._session_key = None
[ "def", "flush", "(", "self", ")", ":", "self", ".", "clear", "(", ")", "self", ".", "delete", "(", ")", "self", ".", "_session_key", "=", "None" ]
[ 270, 4 ]
[ 277, 32 ]
python
en
['en', 'error', 'th']
False
SessionBase.cycle_key
(self)
Creates a new session key, whilst retaining the current session data.
Creates a new session key, whilst retaining the current session data.
def cycle_key(self): """ Creates a new session key, whilst retaining the current session data. """ data = self._session_cache key = self.session_key self.create() self._session_cache = data self.delete(key)
[ "def", "cycle_key", "(", "self", ")", ":", "data", "=", "self", ".", "_session_cache", "key", "=", "self", ".", "session_key", "self", ".", "create", "(", ")", "self", ".", "_session_cache", "=", "data", "self", ".", "delete", "(", "key", ")" ]
[ 279, 4 ]
[ 287, 24 ]
python
en
['en', 'error', 'th']
False
SessionBase.exists
(self, session_key)
Returns True if the given session_key already exists.
Returns True if the given session_key already exists.
def exists(self, session_key): """ Returns True if the given session_key already exists. """ raise NotImplementedError('subclasses of SessionBase must provide an exists() method')
[ "def", "exists", "(", "self", ",", "session_key", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of SessionBase must provide an exists() method'", ")" ]
[ 291, 4 ]
[ 295, 94 ]
python
en
['en', 'error', 'th']
False
SessionBase.create
(self)
Creates a new session instance. Guaranteed to create a new object with a unique key and will have saved the result once (with empty data) before the method returns.
Creates a new session instance. Guaranteed to create a new object with a unique key and will have saved the result once (with empty data) before the method returns.
def create(self): """ Creates a new session instance. Guaranteed to create a new object with a unique key and will have saved the result once (with empty data) before the method returns. """ raise NotImplementedError('subclasses of SessionBase must provide a create() meth...
[ "def", "create", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of SessionBase must provide a create() method'", ")" ]
[ 297, 4 ]
[ 303, 93 ]
python
en
['en', 'error', 'th']
False
SessionBase.save
(self, must_create=False)
Saves the session data. If 'must_create' is True, a new session object is created (otherwise a CreateError exception is raised). Otherwise, save() can update an existing object with the same key.
Saves the session data. If 'must_create' is True, a new session object is created (otherwise a CreateError exception is raised). Otherwise, save() can update an existing object with the same key.
def save(self, must_create=False): """ Saves the session data. If 'must_create' is True, a new session object is created (otherwise a CreateError exception is raised). Otherwise, save() can update an existing object with the same key. """ raise NotImplementedError('subcla...
[ "def", "save", "(", "self", ",", "must_create", "=", "False", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of SessionBase must provide a save() method'", ")" ]
[ 305, 4 ]
[ 311, 91 ]
python
en
['en', 'error', 'th']
False
SessionBase.delete
(self, session_key=None)
Deletes the session data under this key. If the key is None, the current session key value is used.
Deletes the session data under this key. If the key is None, the current session key value is used.
def delete(self, session_key=None): """ Deletes the session data under this key. If the key is None, the current session key value is used. """ raise NotImplementedError('subclasses of SessionBase must provide a delete() method')
[ "def", "delete", "(", "self", ",", "session_key", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of SessionBase must provide a delete() method'", ")" ]
[ 313, 4 ]
[ 318, 93 ]
python
en
['en', 'error', 'th']
False
SessionBase.load
(self)
Loads the session data and returns a dictionary.
Loads the session data and returns a dictionary.
def load(self): """ Loads the session data and returns a dictionary. """ raise NotImplementedError('subclasses of SessionBase must provide a load() method')
[ "def", "load", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of SessionBase must provide a load() method'", ")" ]
[ 320, 4 ]
[ 324, 91 ]
python
en
['en', 'error', 'th']
False
SessionBase.clear_expired
(cls)
Remove expired sessions from the session store. If this operation isn't possible on a given backend, it should raise NotImplementedError. If it isn't necessary, because the backend has a built-in expiration mechanism, it should be a no-op.
Remove expired sessions from the session store.
def clear_expired(cls): """ Remove expired sessions from the session store. If this operation isn't possible on a given backend, it should raise NotImplementedError. If it isn't necessary, because the backend has a built-in expiration mechanism, it should be a no-op. """...
[ "def", "clear_expired", "(", "cls", ")", ":", "raise", "NotImplementedError", "(", "'This backend does not support clear_expired().'", ")" ]
[ 327, 4 ]
[ 335, 83 ]
python
en
['en', 'error', 'th']
False
_check_keys_and_values
(result)
Check that given dict represents equipment data in correct form.
Check that given dict represents equipment data in correct form.
def _check_keys_and_values(result): """ Check that given dict represents equipment data in correct form. """ assert len(result) == 4 # id, name, aliases, category assert result['id'] != '' assert result['name'] == {'fi': 'test equipment'} aliases = result['aliases'] assert len(aliases) ...
[ "def", "_check_keys_and_values", "(", "result", ")", ":", "assert", "len", "(", "result", ")", "==", "4", "# id, name, aliases, category", "assert", "result", "[", "'id'", "]", "!=", "''", "assert", "result", "[", "'name'", "]", "==", "{", "'fi'", ":", "'t...
[ 20, 0 ]
[ 33, 31 ]
python
en
['en', 'error', 'th']
False
test_disallowed_methods
(all_user_types_api_client, list_url, detail_url)
Tests that only safe methods are allowed to equipment list and detail endpoints.
Tests that only safe methods are allowed to equipment list and detail endpoints.
def test_disallowed_methods(all_user_types_api_client, list_url, detail_url): """ Tests that only safe methods are allowed to equipment list and detail endpoints. """ check_only_safe_methods_allowed(all_user_types_api_client, (list_url, detail_url))
[ "def", "test_disallowed_methods", "(", "all_user_types_api_client", ",", "list_url", ",", "detail_url", ")", ":", "check_only_safe_methods_allowed", "(", "all_user_types_api_client", ",", "(", "list_url", ",", "detail_url", ")", ")" ]
[ 37, 0 ]
[ 41, 86 ]
python
en
['en', 'error', 'th']
False
test_get_equipment_list
(api_client, list_url, equipment, equipment_alias)
Tests that equipment list endpoint return equipment data in correct form.
Tests that equipment list endpoint return equipment data in correct form.
def test_get_equipment_list(api_client, list_url, equipment, equipment_alias): """ Tests that equipment list endpoint return equipment data in correct form. """ response = api_client.get(list_url) results = response.data['results'] assert len(results) == 1 _check_keys_and_values(results[0])
[ "def", "test_get_equipment_list", "(", "api_client", ",", "list_url", ",", "equipment", ",", "equipment_alias", ")", ":", "response", "=", "api_client", ".", "get", "(", "list_url", ")", "results", "=", "response", ".", "data", "[", "'results'", "]", "assert",...
[ 45, 0 ]
[ 52, 38 ]
python
en
['en', 'error', 'th']
False
test_get_equipment_detail
(api_client, detail_url, equipment, equipment_alias)
Tests that equipment detail endpoint returns equipment data in correct form.
Tests that equipment detail endpoint returns equipment data in correct form.
def test_get_equipment_detail(api_client, detail_url, equipment, equipment_alias): """ Tests that equipment detail endpoint returns equipment data in correct form. """ response = api_client.get(detail_url) _check_keys_and_values(response.data)
[ "def", "test_get_equipment_detail", "(", "api_client", ",", "detail_url", ",", "equipment", ",", "equipment_alias", ")", ":", "response", "=", "api_client", ".", "get", "(", "detail_url", ")", "_check_keys_and_values", "(", "response", ".", "data", ")" ]
[ 56, 0 ]
[ 61, 41 ]
python
en
['en', 'error', 'th']
False
test_get_equipment_in_resource
(api_client, resource_in_unit, resource_equipment)
Tests that combined resource equipment and equipment data is available via resource endpoint. Equipment aliases should not be included.
Tests that combined resource equipment and equipment data is available via resource endpoint.
def test_get_equipment_in_resource(api_client, resource_in_unit, resource_equipment): """ Tests that combined resource equipment and equipment data is available via resource endpoint. Equipment aliases should not be included. """ response = api_client.get(reverse('resource-detail', kwargs={'pk': re...
[ "def", "test_get_equipment_in_resource", "(", "api_client", ",", "resource_in_unit", ",", "resource_equipment", ")", ":", "response", "=", "api_client", ".", "get", "(", "reverse", "(", "'resource-detail'", ",", "kwargs", "=", "{", "'pk'", ":", "resource_in_unit", ...
[ 65, 0 ]
[ 80, 56 ]
python
en
['en', 'error', 'th']
False