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
convert_slack_workspace_messages
( slack_data_dir: str, users: List[ZerverFieldsT], realm_id: int, slack_user_id_to_zulip_user_id: SlackToZulipUserIDT, slack_recipient_name_to_zulip_recipient_id: SlackToZulipRecipientT, added_channels: AddedChannelsT, added_mpims: AddedMPIMsT, dm_members: DMMembersT, realm: ZerverFi...
Returns: 1. reactions, which is a list of the reactions 2. uploads, which is a list of uploads to be mapped in uploads records.json 3. attachment, which is a list of the attachments
Returns: 1. reactions, which is a list of the reactions 2. uploads, which is a list of uploads to be mapped in uploads records.json 3. attachment, which is a list of the attachments
def convert_slack_workspace_messages( slack_data_dir: str, users: List[ZerverFieldsT], realm_id: int, slack_user_id_to_zulip_user_id: SlackToZulipUserIDT, slack_recipient_name_to_zulip_recipient_id: SlackToZulipRecipientT, added_channels: AddedChannelsT, added_mpims: AddedMPIMsT, dm_memb...
[ "def", "convert_slack_workspace_messages", "(", "slack_data_dir", ":", "str", ",", "users", ":", "List", "[", "ZerverFieldsT", "]", ",", "realm_id", ":", "int", ",", "slack_user_id_to_zulip_user_id", ":", "SlackToZulipUserIDT", ",", "slack_recipient_name_to_zulip_recipien...
[ 660, 0 ]
[ 750, 60 ]
python
en
['en', 'error', 'th']
False
get_messages_iterator
( slack_data_dir: str, added_channels: Dict[str, Any], added_mpims: AddedMPIMsT, dm_members: DMMembersT, )
This function is an iterator that returns all the messages across all Slack channels, in order by timestamp. It's important to not read all the messages into memory at once, because for large imports that can OOM kill.
This function is an iterator that returns all the messages across all Slack channels, in order by timestamp. It's important to not read all the messages into memory at once, because for large imports that can OOM kill.
def get_messages_iterator( slack_data_dir: str, added_channels: Dict[str, Any], added_mpims: AddedMPIMsT, dm_members: DMMembersT, ) -> Iterator[ZerverFieldsT]: """This function is an iterator that returns all the messages across all Slack channels, in order by timestamp. It's important to n...
[ "def", "get_messages_iterator", "(", "slack_data_dir", ":", "str", ",", "added_channels", ":", "Dict", "[", "str", ",", "Any", "]", ",", "added_mpims", ":", "AddedMPIMsT", ",", "dm_members", ":", "DMMembersT", ",", ")", "->", "Iterator", "[", "ZerverFieldsT", ...
[ 753, 0 ]
[ 799, 70 ]
python
en
['en', 'en', 'en']
True
channel_message_to_zerver_message
( realm_id: int, users: List[ZerverFieldsT], slack_user_id_to_zulip_user_id: SlackToZulipUserIDT, slack_recipient_name_to_zulip_recipient_id: SlackToZulipRecipientT, all_messages: List[ZerverFieldsT], zerver_realmemoji: List[ZerverFieldsT], subscriber_map: Dict[int, Set[int]], added_chan...
Returns: 1. zerver_message, which is a list of the messages 2. zerver_usermessage, which is a list of the usermessages 3. zerver_attachment, which is a list of the attachments 4. uploads_list, which is a list of uploads to be mapped in uploads records.json 5. reaction_list, which is a list of a...
Returns: 1. zerver_message, which is a list of the messages 2. zerver_usermessage, which is a list of the usermessages 3. zerver_attachment, which is a list of the attachments 4. uploads_list, which is a list of uploads to be mapped in uploads records.json 5. reaction_list, which is a list of a...
def channel_message_to_zerver_message( realm_id: int, users: List[ZerverFieldsT], slack_user_id_to_zulip_user_id: SlackToZulipUserIDT, slack_recipient_name_to_zulip_recipient_id: SlackToZulipRecipientT, all_messages: List[ZerverFieldsT], zerver_realmemoji: List[ZerverFieldsT], subscriber_map...
[ "def", "channel_message_to_zerver_message", "(", "realm_id", ":", "int", ",", "users", ":", "List", "[", "ZerverFieldsT", "]", ",", "slack_user_id_to_zulip_user_id", ":", "SlackToZulipUserIDT", ",", "slack_recipient_name_to_zulip_recipient_id", ":", "SlackToZulipRecipientT", ...
[ 802, 0 ]
[ 971, 93 ]
python
en
['en', 'error', 'th']
False
build_page_params_for_home_page_load
( request: HttpRequest, user_profile: Optional[UserProfile], realm: Realm, insecure_desktop_app: bool, has_mobile_devices: bool, narrow: List[List[str]], narrow_stream: Optional[Stream], narrow_topic: Optional[str], first_in_realm: bool, prompt_for_invites: bool, needs_tutori...
This function computes page_params for when we load the home page. The page_params data structure gets sent to the client.
This function computes page_params for when we load the home page.
def build_page_params_for_home_page_load( request: HttpRequest, user_profile: Optional[UserProfile], realm: Realm, insecure_desktop_app: bool, has_mobile_devices: bool, narrow: List[List[str]], narrow_stream: Optional[Stream], narrow_topic: Optional[str], first_in_realm: bool, pr...
[ "def", "build_page_params_for_home_page_load", "(", "request", ":", "HttpRequest", ",", "user_profile", ":", "Optional", "[", "UserProfile", "]", ",", "realm", ":", "Realm", ",", "insecure_desktop_app", ":", "bool", ",", "has_mobile_devices", ":", "bool", ",", "na...
[ 103, 0 ]
[ 223, 48 ]
python
en
['en', 'error', 'th']
False
event_dict_type
( required_keys: Sequence[Tuple[str, Any]], optional_keys: Sequence[Tuple[str, Any]] = [], )
This is just a tiny wrapper on DictType, but it provides some minor benefits: - mark clearly that the schema is for a Zulip event - make sure there's a type field - add id field automatically - sanity check that we have no duplicate keys
This is just a tiny wrapper on DictType, but it provides some minor benefits:
def event_dict_type( required_keys: Sequence[Tuple[str, Any]], optional_keys: Sequence[Tuple[str, Any]] = [], ) -> DictType: """ This is just a tiny wrapper on DictType, but it provides some minor benefits: - mark clearly that the schema is for a Zulip event - make sure there's a t...
[ "def", "event_dict_type", "(", "required_keys", ":", "Sequence", "[", "Tuple", "[", "str", ",", "Any", "]", "]", ",", "optional_keys", ":", "Sequence", "[", "Tuple", "[", "str", ",", "Any", "]", "]", "=", "[", "]", ",", ")", "->", "DictType", ":", ...
[ 242, 0 ]
[ 266, 5 ]
python
en
['en', 'error', 'th']
False
schema
( var_name: str, data_type: Any, )
Returns a YAML-like string for our data type; these are used for pretty-printing and comparison between the OpenAPI type definitions and these Python data types, as part of schema is a glorified repr of a data type, but it also includes a var_name you pass in, plus we dumb things down a bit to match ou...
Returns a YAML-like string for our data type; these are used for pretty-printing and comparison between the OpenAPI type definitions and these Python data types, as part of
def schema( var_name: str, data_type: Any, ) -> str: """Returns a YAML-like string for our data type; these are used for pretty-printing and comparison between the OpenAPI type definitions and these Python data types, as part of schema is a glorified repr of a data type, but it also includes a ...
[ "def", "schema", "(", "var_name", ":", "str", ",", "data_type", ":", "Any", ",", ")", "->", "str", ":", "if", "hasattr", "(", "data_type", ",", "\"schema\"", ")", ":", "return", "data_type", ".", "schema", "(", "var_name", ")", "if", "data_type", "in",...
[ 278, 0 ]
[ 294, 53 ]
python
en
['en', 'en', 'en']
True
check_data
( data_type: Any, var_name: str, val: Any, )
Check that val conforms to our data_type
Check that val conforms to our data_type
def check_data( data_type: Any, var_name: str, val: Any, ) -> None: """Check that val conforms to our data_type""" if hasattr(data_type, "check_data"): data_type.check_data(var_name, val) return if not isinstance(val, data_type): raise AssertionError(f"{var_name} is not t...
[ "def", "check_data", "(", "data_type", ":", "Any", ",", "var_name", ":", "str", ",", "val", ":", "Any", ",", ")", "->", "None", ":", "if", "hasattr", "(", "data_type", ",", "\"check_data\"", ")", ":", "data_type", ".", "check_data", "(", "var_name", ",...
[ 297, 0 ]
[ 307, 67 ]
python
en
['en', 'en', 'en']
True
FileBasedCache._cull
(self)
Remove random cache entries if max_entries is reached at a ratio of num_entries / cull_frequency. A value of 0 for CULL_FREQUENCY means that the entire cache will be purged.
Remove random cache entries if max_entries is reached at a ratio of num_entries / cull_frequency. A value of 0 for CULL_FREQUENCY means that the entire cache will be purged.
def _cull(self): """ Remove random cache entries if max_entries is reached at a ratio of num_entries / cull_frequency. A value of 0 for CULL_FREQUENCY means that the entire cache will be purged. """ filelist = self._list_cache_files() num_entries = len(filelist) ...
[ "def", "_cull", "(", "self", ")", ":", "filelist", "=", "self", ".", "_list_cache_files", "(", ")", "num_entries", "=", "len", "(", "filelist", ")", "if", "num_entries", "<", "self", ".", "_max_entries", ":", "return", "# return early if no culling is required",...
[ 96, 4 ]
[ 112, 31 ]
python
en
['en', 'error', 'th']
False
FileBasedCache._key_to_file
(self, key, version=None)
Convert a key into a cache file path. Basically this is the root cache path joined with the md5sum of the key and a suffix.
Convert a key into a cache file path. Basically this is the root cache path joined with the md5sum of the key and a suffix.
def _key_to_file(self, key, version=None): """ Convert a key into a cache file path. Basically this is the root cache path joined with the md5sum of the key and a suffix. """ key = self.make_key(key, version=version) self.validate_key(key) return os.path.join(self...
[ "def", "_key_to_file", "(", "self", ",", "key", ",", "version", "=", "None", ")", ":", "key", "=", "self", ".", "make_key", "(", "key", ",", "version", "=", "version", ")", "self", ".", "validate_key", "(", "key", ")", "return", "os", ".", "path", ...
[ 117, 4 ]
[ 125, 72 ]
python
en
['en', 'error', 'th']
False
FileBasedCache.clear
(self)
Remove all the cache files.
Remove all the cache files.
def clear(self): """ Remove all the cache files. """ for fname in self._list_cache_files(): self._delete(fname)
[ "def", "clear", "(", "self", ")", ":", "for", "fname", "in", "self", ".", "_list_cache_files", "(", ")", ":", "self", ".", "_delete", "(", "fname", ")" ]
[ 127, 4 ]
[ 132, 31 ]
python
en
['en', 'error', 'th']
False
FileBasedCache._is_expired
(self, f)
Take an open cache file `f` and delete it if it's expired.
Take an open cache file `f` and delete it if it's expired.
def _is_expired(self, f): """ Take an open cache file `f` and delete it if it's expired. """ try: exp = pickle.load(f) except EOFError: exp = 0 # An empty file is considered expired. if exp is not None and exp < time.time(): f.close() ...
[ "def", "_is_expired", "(", "self", ",", "f", ")", ":", "try", ":", "exp", "=", "pickle", ".", "load", "(", "f", ")", "except", "EOFError", ":", "exp", "=", "0", "# An empty file is considered expired.", "if", "exp", "is", "not", "None", "and", "exp", "...
[ 134, 4 ]
[ 146, 20 ]
python
en
['en', 'error', 'th']
False
FileBasedCache._list_cache_files
(self)
Get a list of paths to all the cache files. These are all the files in the root cache dir that end on the cache_suffix.
Get a list of paths to all the cache files. These are all the files in the root cache dir that end on the cache_suffix.
def _list_cache_files(self): """ Get a list of paths to all the cache files. These are all the files in the root cache dir that end on the cache_suffix. """ return [ os.path.join(self._dir, fname) for fname in glob.glob1(self._dir, '*%s' % self.cache_suffi...
[ "def", "_list_cache_files", "(", "self", ")", ":", "return", "[", "os", ".", "path", ".", "join", "(", "self", ".", "_dir", ",", "fname", ")", "for", "fname", "in", "glob", ".", "glob1", "(", "self", ".", "_dir", ",", "'*%s'", "%", "self", ".", "...
[ 148, 4 ]
[ 156, 9 ]
python
en
['en', 'error', 'th']
False
Command.show_list
(self, connection, app_names=None)
Show a list of all migrations on the system, or only those of some named apps.
Show a list of all migrations on the system, or only those of some named apps.
def show_list(self, connection, app_names=None): """ Show a list of all migrations on the system, or only those of some named apps. """ # Load migrations from disk/DB loader = MigrationLoader(connection, ignore_no_migrations=True) graph = loader.graph # If...
[ "def", "show_list", "(", "self", ",", "connection", ",", "app_names", "=", "None", ")", ":", "# Load migrations from disk/DB", "loader", "=", "MigrationLoader", "(", "connection", ",", "ignore_no_migrations", "=", "True", ")", "graph", "=", "loader", ".", "graph...
[ 64, 4 ]
[ 102, 71 ]
python
en
['en', 'error', 'th']
False
Command.show_plan
(self, connection, app_names=None)
Show all known migrations (or only those of the specified app_names) in the order they will be applied.
Show all known migrations (or only those of the specified app_names) in the order they will be applied.
def show_plan(self, connection, app_names=None): """ Show all known migrations (or only those of the specified app_names) in the order they will be applied. """ # Load migrations from disk/DB loader = MigrationLoader(connection) graph = loader.graph if app...
[ "def", "show_plan", "(", "self", ",", "connection", ",", "app_names", "=", "None", ")", ":", "# Load migrations from disk/DB", "loader", "=", "MigrationLoader", "(", "connection", ")", "graph", "=", "loader", ".", "graph", "if", "app_names", ":", "self", ".", ...
[ 104, 4 ]
[ 146, 66 ]
python
en
['en', 'error', 'th']
False
register_handler
(handler)
Install application-specific BUFR image handler. :param handler: Handler object.
Install application-specific BUFR image handler.
def register_handler(handler): """ Install application-specific BUFR image handler. :param handler: Handler object. """ global _handler _handler = handler
[ "def", "register_handler", "(", "handler", ")", ":", "global", "_handler", "_handler", "=", "handler" ]
[ 16, 0 ]
[ 23, 22 ]
python
en
['en', 'error', 'th']
False
mnist_tutorial
( train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, clean_train=CLEAN_TRAIN, testing=False, backprop_through_attack=BACKPROP_THROUGH_ATTACK, nb_filters=NB_FILTERS, num_threads=None, l...
MNIST cleverhans tutorial :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param nb_epochs: number of epochs to train model :param ...
MNIST cleverhans tutorial :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param nb_epochs: number of epochs to train model :param ...
def mnist_tutorial( train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, clean_train=CLEAN_TRAIN, testing=False, backprop_through_attack=BACKPROP_THROUGH_ATTACK, nb_filters=NB_FILTERS, num_t...
[ "def", "mnist_tutorial", "(", "train_start", "=", "0", ",", "train_end", "=", "60000", ",", "test_start", "=", "0", ",", "test_end", "=", "10000", ",", "nb_epochs", "=", "NB_EPOCHS", ",", "batch_size", "=", "BATCH_SIZE", ",", "learning_rate", "=", "LEARNING_...
[ 35, 0 ]
[ 250, 17 ]
python
en
['en', 'error', 'th']
False
main
(argv=None)
Run the tutorial using command line flags
Run the tutorial using command line flags
def main(argv=None): """ Run the tutorial using command line flags """ from cleverhans_tutorials import check_installation check_installation(__file__) mnist_tutorial( nb_epochs=FLAGS.nb_epochs, batch_size=FLAGS.batch_size, learning_rate=FLAGS.learning_rate, cle...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "from", "cleverhans_tutorials", "import", "check_installation", "check_installation", "(", "__file__", ")", "mnist_tutorial", "(", "nb_epochs", "=", "FLAGS", ".", "nb_epochs", ",", "batch_size", "=", "FLAGS", "....
[ 253, 0 ]
[ 268, 5 ]
python
en
['en', 'error', 'th']
False
train
( sess, loss, x_train, y_train, init_all=False, evaluate=None, feed=None, args=None, rng=None, var_list=None, fprop_args=None, optimizer=None, devices=None, x_batch_preprocessor=None, use_ema=False, ema_decay=0.998, run_canary=None, loss_threshold=...
Run (optionally multi-replica, synchronous) training to minimize `loss` :param sess: TF session to use when training the graph :param loss: tensor, the loss to minimize :param x_train: numpy array with training inputs or tf Dataset :param y_train: numpy array with training outputs or tf Dataset ...
Run (optionally multi-replica, synchronous) training to minimize `loss` :param sess: TF session to use when training the graph :param loss: tensor, the loss to minimize :param x_train: numpy array with training inputs or tf Dataset :param y_train: numpy array with training outputs or tf Dataset ...
def train( sess, loss, x_train, y_train, init_all=False, evaluate=None, feed=None, args=None, rng=None, var_list=None, fprop_args=None, optimizer=None, devices=None, x_batch_preprocessor=None, use_ema=False, ema_decay=0.998, run_canary=None, loss_t...
[ "def", "train", "(", "sess", ",", "loss", ",", "x_train", ",", "y_train", ",", "init_all", "=", "False", ",", "evaluate", "=", "None", ",", "feed", "=", "None", ",", "args", "=", "None", ",", "rng", "=", "None", ",", "var_list", "=", "None", ",", ...
[ 37, 0 ]
[ 297, 15 ]
python
en
['en', 'error', 'th']
False
avg_grads
(tower_grads)
Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. The inner list is over the gradie...
Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients. The inner list is over the gradie...
def avg_grads(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradients...
[ "def", "avg_grads", "(", "tower_grads", ")", ":", "if", "len", "(", "tower_grads", ")", "==", "1", ":", "return", "tower_grads", "[", "0", "]", "average_grads", "=", "[", "]", "for", "grad_and_vars", "in", "zip", "(", "*", "tower_grads", ")", ":", "# N...
[ 300, 0 ]
[ 332, 24 ]
python
en
['en', 'en', 'en']
True
MigrationWriter.as_string
(self)
Return a string of the file contents.
Return a string of the file contents.
def as_string(self): """Return a string of the file contents.""" items = { "replaces_str": "", "initial_str": "", } imports = set() # Deconstruct operations operations = [] for operation in self.migration.operations: operation...
[ "def", "as_string", "(", "self", ")", ":", "items", "=", "{", "\"replaces_str\"", ":", "\"\"", ",", "\"initial_str\"", ":", "\"\"", ",", "}", "imports", "=", "set", "(", ")", "# Deconstruct operations", "operations", "=", "[", "]", "for", "operation", "in"...
[ 128, 4 ]
[ 198, 41 ]
python
en
['en', 'en', 'en']
True
PyAccess.__setitem__
(self, xy, color)
Modifies the pixel at x,y. The color is given as a single numerical value for single band images, and a tuple for multi-band images :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param color: The pixel value.
Modifies the pixel at x,y. The color is given as a single numerical value for single band images, and a tuple for multi-band images
def __setitem__(self, xy, color): """ Modifies the pixel at x,y. The color is given as a single numerical value for single band images, and a tuple for multi-band images :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :param col...
[ "def", "__setitem__", "(", "self", ",", "xy", ",", "color", ")", ":", "if", "self", ".", "readonly", ":", "raise", "ValueError", "(", "\"Attempt to putpixel a read only image\"", ")", "(", "x", ",", "y", ")", "=", "xy", "if", "x", "<", "0", ":", "x", ...
[ 70, 4 ]
[ 97, 42 ]
python
en
['en', 'error', 'th']
False
PyAccess.__getitem__
(self, xy)
Returns the pixel at x,y. The pixel is returned as a single value for single band images or a tuple for multiple band images :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: a pixel value for single band images, a tuple of ...
Returns the pixel at x,y. The pixel is returned as a single value for single band images or a tuple for multiple band images
def __getitem__(self, xy): """ Returns the pixel at x,y. The pixel is returned as a single value for single band images or a tuple for multiple band images :param xy: The pixel coordinate, given as (x, y). See :ref:`coordinate-system`. :returns: a pixel value f...
[ "def", "__getitem__", "(", "self", ",", "xy", ")", ":", "(", "x", ",", "y", ")", "=", "xy", "if", "x", "<", "0", ":", "x", "=", "self", ".", "xsize", "+", "x", "if", "y", "<", "0", ":", "y", "=", "self", ".", "ysize", "+", "y", "(", "x"...
[ 99, 4 ]
[ 116, 35 ]
python
en
['en', 'error', 'th']
False
AggregationTests.test_aggregates_in_where_clause
(self)
Regression test for #12822: DatabaseError: aggregates not allowed in WHERE clause Tests that the subselect works and returns results equivalent to a query with the IDs listed. Before the corresponding fix for this bug, this test passed in 1.1 and failed in 1.2-beta (tr...
Regression test for #12822: DatabaseError: aggregates not allowed in WHERE clause
def test_aggregates_in_where_clause(self): """ Regression test for #12822: DatabaseError: aggregates not allowed in WHERE clause Tests that the subselect works and returns results equivalent to a query with the IDs listed. Before the corresponding fix for this bug, this...
[ "def", "test_aggregates_in_where_clause", "(", "self", ")", ":", "qs", "=", "Book", ".", "objects", ".", "values", "(", "'contact'", ")", ".", "annotate", "(", "Max", "(", "'id'", ")", ")", "qs", "=", "qs", ".", "order_by", "(", "'contact'", ")", ".", ...
[ 25, 4 ]
[ 43, 46 ]
python
en
['en', 'error', 'th']
False
AggregationTests.test_aggregates_in_where_clause_pre_eval
(self)
Regression test for #12822: DatabaseError: aggregates not allowed in WHERE clause Same as the above test, but evaluates the queryset for the subquery before it's used as a subquery. Before the corresponding fix for this bug, this test failed in both 1.1 and 1.2-beta (t...
Regression test for #12822: DatabaseError: aggregates not allowed in WHERE clause
def test_aggregates_in_where_clause_pre_eval(self): """ Regression test for #12822: DatabaseError: aggregates not allowed in WHERE clause Same as the above test, but evaluates the queryset for the subquery before it's used as a subquery. Before the corresponding fix for...
[ "def", "test_aggregates_in_where_clause_pre_eval", "(", "self", ")", ":", "qs", "=", "Book", ".", "objects", ".", "values", "(", "'contact'", ")", ".", "annotate", "(", "Max", "(", "'id'", ")", ")", "qs", "=", "qs", ".", "order_by", "(", "'contact'", ")"...
[ 45, 4 ]
[ 64, 46 ]
python
en
['en', 'error', 'th']
False
AggregationTests.test_annotate_with_extra
(self)
Regression test for #11916: Extra params + aggregation creates incorrect SQL.
Regression test for #11916: Extra params + aggregation creates incorrect SQL.
def test_annotate_with_extra(self): """ Regression test for #11916: Extra params + aggregation creates incorrect SQL. """ # Oracle doesn't support subqueries in group by clause shortest_book_sql = """ SELECT name FROM aggregation_regress_book b WHE...
[ "def", "test_annotate_with_extra", "(", "self", ")", ":", "# Oracle doesn't support subqueries in group by clause", "shortest_book_sql", "=", "\"\"\"\n SELECT name\n FROM aggregation_regress_book b\n WHERE b.publisher_id = aggregation_regress_publisher.id\n ORDER BY b.p...
[ 67, 4 ]
[ 86, 16 ]
python
en
['en', 'error', 'th']
False
AggregationTests.test_annotate_joins
(self)
Test that the base table's join isn't promoted to LOUTER. This could cause the query generation to fail if there is an exclude() for fk-field in the query, too. Refs #19087.
Test that the base table's join isn't promoted to LOUTER. This could cause the query generation to fail if there is an exclude() for fk-field in the query, too. Refs #19087.
def test_annotate_joins(self): """ Test that the base table's join isn't promoted to LOUTER. This could cause the query generation to fail if there is an exclude() for fk-field in the query, too. Refs #19087. """ qs = Book.objects.annotate(n=Count('pk')) self.asse...
[ "def", "test_annotate_joins", "(", "self", ")", ":", "qs", "=", "Book", ".", "objects", ".", "annotate", "(", "n", "=", "Count", "(", "'pk'", ")", ")", "self", ".", "assertIs", "(", "qs", ".", "query", ".", "alias_map", "[", "'aggregation_regress_book'",...
[ 896, 4 ]
[ 905, 58 ]
python
en
['en', 'error', 'th']
False
AggregationTests.test_aggregation_with_generic_reverse_relation
(self)
Regression test for #10870: Aggregates with joins ignore extra filters provided by setup_joins tests aggregations with generic reverse relations
Regression test for #10870: Aggregates with joins ignore extra filters provided by setup_joins
def test_aggregation_with_generic_reverse_relation(self): """ Regression test for #10870: Aggregates with joins ignore extra filters provided by setup_joins tests aggregations with generic reverse relations """ django_book = Book.objects.get(name='Practical Django Proje...
[ "def", "test_aggregation_with_generic_reverse_relation", "(", "self", ")", ":", "django_book", "=", "Book", ".", "objects", ".", "get", "(", "name", "=", "'Practical Django Projects'", ")", "ItemTag", ".", "objects", ".", "create", "(", "object_id", "=", "django_b...
[ 1000, 4 ]
[ 1034, 9 ]
python
en
['en', 'error', 'th']
False
AggregationTests.test_ticket_11293_q_immutable
(self)
Check that splitting a q object to parts for where/having doesn't alter the original q-object.
Check that splitting a q object to parts for where/having doesn't alter the original q-object.
def test_ticket_11293_q_immutable(self): """ Check that splitting a q object to parts for where/having doesn't alter the original q-object. """ q1 = Q(isbn='') q2 = Q(authors__count__gt=1) query = Book.objects.annotate(Count('authors')) query.filter(q1 | q...
[ "def", "test_ticket_11293_q_immutable", "(", "self", ")", ":", "q1", "=", "Q", "(", "isbn", "=", "''", ")", "q2", "=", "Q", "(", "authors__count__gt", "=", "1", ")", "query", "=", "Book", ".", "objects", ".", "annotate", "(", "Count", "(", "'authors'",...
[ 1091, 4 ]
[ 1100, 45 ]
python
en
['en', 'error', 'th']
False
AggregationTests.test_fobj_group_by
(self)
Check that an F() object referring to related column works correctly in group by.
Check that an F() object referring to related column works correctly in group by.
def test_fobj_group_by(self): """ Check that an F() object referring to related column works correctly in group by. """ qs = Book.objects.annotate( acount=Count('authors') ).filter( acount=F('publisher__num_awards') ) self.assertQue...
[ "def", "test_fobj_group_by", "(", "self", ")", ":", "qs", "=", "Book", ".", "objects", ".", "annotate", "(", "acount", "=", "Count", "(", "'authors'", ")", ")", ".", "filter", "(", "acount", "=", "F", "(", "'publisher__num_awards'", ")", ")", "self", "...
[ 1102, 4 ]
[ 1114, 29 ]
python
en
['en', 'error', 'th']
False
AggregationTests.test_annotate_reserved_word
(self)
Regression #18333 - Ensure annotated column name is properly quoted.
Regression #18333 - Ensure annotated column name is properly quoted.
def test_annotate_reserved_word(self): """ Regression #18333 - Ensure annotated column name is properly quoted. """ vals = Book.objects.annotate(select=Count('authors__id')).aggregate(Sum('select'), Avg('select')) self.assertEqual(vals, { 'select__sum': 10, ...
[ "def", "test_annotate_reserved_word", "(", "self", ")", ":", "vals", "=", "Book", ".", "objects", ".", "annotate", "(", "select", "=", "Count", "(", "'authors__id'", ")", ")", ".", "aggregate", "(", "Sum", "(", "'select'", ")", ",", "Avg", "(", "'select'...
[ 1116, 4 ]
[ 1124, 10 ]
python
en
['en', 'error', 'th']
False
Config._cast_boolean
(self, value)
Helper to convert config values to boolean as ConfigParser do.
Helper to convert config values to boolean as ConfigParser do.
def _cast_boolean(self, value): """ Helper to convert config values to boolean as ConfigParser do. """ value = str(value) return bool(value) if value == '' else bool(strtobool(value))
[ "def", "_cast_boolean", "(", "self", ",", "value", ")", ":", "value", "=", "str", "(", "value", ")", "return", "bool", "(", "value", ")", "if", "value", "==", "''", "else", "bool", "(", "strtobool", "(", "value", ")", ")" ]
[ 44, 4 ]
[ 49, 69 ]
python
en
['en', 'error', 'th']
False
Config.get
(self, option, default=undefined, cast=undefined)
Return the value for option or default if defined.
Return the value for option or default if defined.
def get(self, option, default=undefined, cast=undefined): """ Return the value for option or default if defined. """ # We can't avoid __contains__ because value may be empty. if option in os.environ: value = os.environ[option] elif option in self.repository: ...
[ "def", "get", "(", "self", ",", "option", ",", "default", "=", "undefined", ",", "cast", "=", "undefined", ")", ":", "# We can't avoid __contains__ because value may be empty.", "if", "option", "in", "os", ".", "environ", ":", "value", "=", "os", ".", "environ...
[ 55, 4 ]
[ 76, 26 ]
python
en
['en', 'error', 'th']
False
Config.__call__
(self, *args, **kwargs)
Convenient shortcut to get.
Convenient shortcut to get.
def __call__(self, *args, **kwargs): """ Convenient shortcut to get. """ return self.get(*args, **kwargs)
[ "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "get", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 78, 4 ]
[ 82, 40 ]
python
en
['en', 'error', 'th']
False
Csv.__init__
(self, cast=text_type, delimiter=',', strip=string.whitespace, post_process=list)
Parameters: cast -- callable that transforms the item just before it's added to the list. delimiter -- string of delimiters chars passed to shlex. strip -- string of non-relevant characters to be passed to str.strip after the split. post_process -- callable to post process all c...
Parameters: cast -- callable that transforms the item just before it's added to the list. delimiter -- string of delimiters chars passed to shlex. strip -- string of non-relevant characters to be passed to str.strip after the split. post_process -- callable to post process all c...
def __init__(self, cast=text_type, delimiter=',', strip=string.whitespace, post_process=list): """ Parameters: cast -- callable that transforms the item just before it's added to the list. delimiter -- string of delimiters chars passed to shlex. strip -- string of non-relevant ch...
[ "def", "__init__", "(", "self", ",", "cast", "=", "text_type", ",", "delimiter", "=", "','", ",", "strip", "=", "string", ".", "whitespace", ",", "post_process", "=", "list", ")", ":", "self", ".", "cast", "=", "cast", "self", ".", "delimiter", "=", ...
[ 212, 4 ]
[ 223, 40 ]
python
en
['en', 'error', 'th']
False
Csv.__call__
(self, value)
The actual transformation
The actual transformation
def __call__(self, value): """The actual transformation""" transform = lambda s: self.cast(s.strip(self.strip)) splitter = shlex(value, posix=True) splitter.whitespace = self.delimiter splitter.whitespace_split = True return self.post_process(transform(s) for s in split...
[ "def", "__call__", "(", "self", ",", "value", ")", ":", "transform", "=", "lambda", "s", ":", "self", ".", "cast", "(", "s", ".", "strip", "(", "self", ".", "strip", ")", ")", "splitter", "=", "shlex", "(", "value", ",", "posix", "=", "True", ")"...
[ 225, 4 ]
[ 233, 64 ]
python
en
['en', 'en', 'en']
True
LayerMapping.__init__
(self, model, data, mapping, layer=0, source_srs=None, encoding='utf-8', transaction_mode='commit_on_success', transform=True, unique=None, using=None)
A LayerMapping object is initialized using the given Model (not an instance), a DataSource (or string path to an OGR-supported data file), and a mapping dictionary. See the module level docstring for more details and keyword argument usage.
A LayerMapping object is initialized using the given Model (not an instance), a DataSource (or string path to an OGR-supported data file), and a mapping dictionary. See the module level docstring for more details and keyword argument usage.
def __init__(self, model, data, mapping, layer=0, source_srs=None, encoding='utf-8', transaction_mode='commit_on_success', transform=True, unique=None, using=None): """ A LayerMapping object is initialized using the given Model (not an instance), ...
[ "def", "__init__", "(", "self", ",", "model", ",", "data", ",", "mapping", ",", "layer", "=", "0", ",", "source_srs", "=", "None", ",", "encoding", "=", "'utf-8'", ",", "transaction_mode", "=", "'commit_on_success'", ",", "transform", "=", "True", ",", "...
[ 75, 4 ]
[ 144, 87 ]
python
en
['en', 'error', 'th']
False
LayerMapping.check_fid_range
(self, fid_range)
This checks the `fid_range` keyword.
This checks the `fid_range` keyword.
def check_fid_range(self, fid_range): "This checks the `fid_range` keyword." if fid_range: if isinstance(fid_range, (tuple, list)): return slice(*fid_range) elif isinstance(fid_range, slice): return fid_range else: raise...
[ "def", "check_fid_range", "(", "self", ",", "fid_range", ")", ":", "if", "fid_range", ":", "if", "isinstance", "(", "fid_range", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "slice", "(", "*", "fid_range", ")", "elif", "isinstance", "(", "f...
[ 147, 4 ]
[ 157, 23 ]
python
en
['en', 'hmn', 'en']
True
LayerMapping.check_layer
(self)
This checks the Layer metadata, and ensures that it is compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer.
This checks the Layer metadata, and ensures that it is compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer.
def check_layer(self): """ This checks the Layer metadata, and ensures that it is compatible with the mapping information and model. Unlike previous revisions, there is no need to increment through each feature in the Layer. """ # The geometry field of the model is set h...
[ "def", "check_layer", "(", "self", ")", ":", "# The geometry field of the model is set here.", "# TODO: Support more than one geometry field / model. However, this", "# depends on the GDAL Driver in use.", "self", ".", "geom_field", "=", "False", "self", ".", "fields", "=", "{",...
[ 159, 4 ]
[ 254, 48 ]
python
en
['en', 'error', 'th']
False
LayerMapping.check_srs
(self, source_srs)
Checks the compatibility of the given spatial reference object.
Checks the compatibility of the given spatial reference object.
def check_srs(self, source_srs): "Checks the compatibility of the given spatial reference object." if isinstance(source_srs, SpatialReference): sr = source_srs elif isinstance(source_srs, self.spatial_backend.spatial_ref_sys()): sr = source_srs.srs elif isinstanc...
[ "def", "check_srs", "(", "self", ",", "source_srs", ")", ":", "if", "isinstance", "(", "source_srs", ",", "SpatialReference", ")", ":", "sr", "=", "source_srs", "elif", "isinstance", "(", "source_srs", ",", "self", ".", "spatial_backend", ".", "spatial_ref_sys...
[ 256, 4 ]
[ 272, 21 ]
python
en
['en', 'en', 'en']
True
LayerMapping.check_unique
(self, unique)
Checks the `unique` keyword parameter -- may be a sequence or string.
Checks the `unique` keyword parameter -- may be a sequence or string.
def check_unique(self, unique): "Checks the `unique` keyword parameter -- may be a sequence or string." if isinstance(unique, (list, tuple)): # List of fields to determine uniqueness with for attr in unique: if attr not in self.mapping: raise V...
[ "def", "check_unique", "(", "self", ",", "unique", ")", ":", "if", "isinstance", "(", "unique", ",", "(", "list", ",", "tuple", ")", ")", ":", "# List of fields to determine uniqueness with", "for", "attr", "in", "unique", ":", "if", "attr", "not", "in", "...
[ 274, 4 ]
[ 286, 97 ]
python
en
['en', 'en', 'en']
True
LayerMapping.feature_kwargs
(self, feat)
Given an OGR Feature, this will return a dictionary of keyword arguments for constructing the mapped model.
Given an OGR Feature, this will return a dictionary of keyword arguments for constructing the mapped model.
def feature_kwargs(self, feat): """ Given an OGR Feature, this will return a dictionary of keyword arguments for constructing the mapped model. """ # The keyword arguments for model construction. kwargs = {} # Incrementing through each model field and OGR field i...
[ "def", "feature_kwargs", "(", "self", ",", "feat", ")", ":", "# The keyword arguments for model construction.", "kwargs", "=", "{", "}", "# Incrementing through each model field and OGR field in the", "# dictionary mapping.", "for", "field_name", ",", "ogr_name", "in", "self"...
[ 289, 4 ]
[ 320, 21 ]
python
en
['en', 'error', 'th']
False
LayerMapping.unique_kwargs
(self, kwargs)
Given the feature keyword arguments (from `feature_kwargs`) this routine will construct and return the uniqueness keyword arguments -- a subset of the feature kwargs.
Given the feature keyword arguments (from `feature_kwargs`) this routine will construct and return the uniqueness keyword arguments -- a subset of the feature kwargs.
def unique_kwargs(self, kwargs): """ Given the feature keyword arguments (from `feature_kwargs`) this routine will construct and return the uniqueness keyword arguments -- a subset of the feature kwargs. """ if isinstance(self.unique, six.string_types): return...
[ "def", "unique_kwargs", "(", "self", ",", "kwargs", ")", ":", "if", "isinstance", "(", "self", ".", "unique", ",", "six", ".", "string_types", ")", ":", "return", "{", "self", ".", "unique", ":", "kwargs", "[", "self", ".", "unique", "]", "}", "else"...
[ 322, 4 ]
[ 331, 66 ]
python
en
['en', 'error', 'th']
False
LayerMapping.verify_ogr_field
(self, ogr_field, model_field)
Verifies if the OGR Field contents are acceptable to the Django model field. If they are, the verified value is returned, otherwise the proper exception is raised.
Verifies if the OGR Field contents are acceptable to the Django model field. If they are, the verified value is returned, otherwise the proper exception is raised.
def verify_ogr_field(self, ogr_field, model_field): """ Verifies if the OGR Field contents are acceptable to the Django model field. If they are, the verified value is returned, otherwise the proper exception is raised. """ if (isinstance(ogr_field, OFTString) and ...
[ "def", "verify_ogr_field", "(", "self", ",", "ogr_field", ",", "model_field", ")", ":", "if", "(", "isinstance", "(", "ogr_field", ",", "OFTString", ")", "and", "isinstance", "(", "model_field", ",", "(", "models", ".", "CharField", ",", "models", ".", "Te...
[ 334, 4 ]
[ 390, 18 ]
python
en
['en', 'error', 'th']
False
LayerMapping.verify_fk
(self, feat, rel_model, rel_mapping)
Given an OGR Feature, the related model and its dictionary mapping, this routine will retrieve the related model for the ForeignKey mapping.
Given an OGR Feature, the related model and its dictionary mapping, this routine will retrieve the related model for the ForeignKey mapping.
def verify_fk(self, feat, rel_model, rel_mapping): """ Given an OGR Feature, the related model and its dictionary mapping, this routine will retrieve the related model for the ForeignKey mapping. """ # TODO: It is expensive to retrieve a model for every record -- ...
[ "def", "verify_fk", "(", "self", ",", "feat", ",", "rel_model", ",", "rel_mapping", ")", ":", "# TODO: It is expensive to retrieve a model for every record --", "# explore if an efficient mechanism exists for caching related", "# ForeignKey models.", "# Constructing and verifying the...
[ 392, 4 ]
[ 414, 13 ]
python
en
['en', 'error', 'th']
False
LayerMapping.verify_geom
(self, geom, model_field)
Verifies the geometry -- will construct and return a GeometryCollection if necessary (for example if the model field is MultiPolygonField while the mapped shapefile only contains Polygons).
Verifies the geometry -- will construct and return a GeometryCollection if necessary (for example if the model field is MultiPolygonField while the mapped shapefile only contains Polygons).
def verify_geom(self, geom, model_field): """ Verifies the geometry -- will construct and return a GeometryCollection if necessary (for example if the model field is MultiPolygonField while the mapped shapefile only contains Polygons). """ # Downgrade a 3D geom to a 2D on...
[ "def", "verify_geom", "(", "self", ",", "geom", ",", "model_field", ")", ":", "# Downgrade a 3D geom to a 2D one, if necessary.", "if", "self", ".", "coord_dim", "!=", "geom", ".", "coord_dim", ":", "geom", ".", "coord_dim", "=", "self", ".", "coord_dim", "if", ...
[ 416, 4 ]
[ 441, 20 ]
python
en
['en', 'error', 'th']
False
LayerMapping.coord_transform
(self)
Returns the coordinate transformation object.
Returns the coordinate transformation object.
def coord_transform(self): "Returns the coordinate transformation object." SpatialRefSys = self.spatial_backend.spatial_ref_sys() try: # Getting the target spatial reference system target_srs = SpatialRefSys.objects.using(self.using).get(srid=self.geo_field.srid).srs ...
[ "def", "coord_transform", "(", "self", ")", ":", "SpatialRefSys", "=", "self", ".", "spatial_backend", ".", "spatial_ref_sys", "(", ")", "try", ":", "# Getting the target spatial reference system", "target_srs", "=", "SpatialRefSys", ".", "objects", ".", "using", "(...
[ 444, 4 ]
[ 455, 81 ]
python
en
['en', 'en', 'en']
True
LayerMapping.geometry_field
(self)
Returns the GeometryField instance associated with the geographic column.
Returns the GeometryField instance associated with the geographic column.
def geometry_field(self): "Returns the GeometryField instance associated with the geographic column." # Use the `get_field_by_name` on the model's options so that we # get the correct field instance if there's model inheritance. opts = self.model._meta fld, model, direct, m2m = o...
[ "def", "geometry_field", "(", "self", ")", ":", "# Use the `get_field_by_name` on the model's options so that we", "# get the correct field instance if there's model inheritance.", "opts", "=", "self", ".", "model", ".", "_meta", "fld", ",", "model", ",", "direct", ",", "m2...
[ 457, 4 ]
[ 463, 18 ]
python
en
['en', 'en', 'en']
True
LayerMapping.make_multi
(self, geom_type, model_field)
Given the OGRGeomType for a geometry and its associated GeometryField, determine whether the geometry should be turned into a GeometryCollection.
Given the OGRGeomType for a geometry and its associated GeometryField, determine whether the geometry should be turned into a GeometryCollection.
def make_multi(self, geom_type, model_field): """ Given the OGRGeomType for a geometry and its associated GeometryField, determine whether the geometry should be turned into a GeometryCollection. """ return (geom_type.num in self.MULTI_TYPES and model_field.__clas...
[ "def", "make_multi", "(", "self", ",", "geom_type", ",", "model_field", ")", ":", "return", "(", "geom_type", ".", "num", "in", "self", ".", "MULTI_TYPES", "and", "model_field", ".", "__class__", ".", "__name__", "==", "'Multi%s'", "%", "geom_type", ".", "...
[ 465, 4 ]
[ 471, 79 ]
python
en
['en', 'error', 'th']
False
LayerMapping.save
(self, verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False)
Saves the contents from the OGR DataSource Layer into the database according to the mapping dictionary given at initialization. Keyword Parameters: verbose: If set, information will be printed subsequent to each model save executed on the database. fid_...
Saves the contents from the OGR DataSource Layer into the database according to the mapping dictionary given at initialization.
def save(self, verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False): """ Saves the contents from the OGR DataSource Layer into the database according to the mapping dictionary given at initialization. Keyword Parameters:...
[ "def", "save", "(", "self", ",", "verbose", "=", "False", ",", "fid_range", "=", "False", ",", "step", "=", "False", ",", "progress", "=", "False", ",", "silent", "=", "False", ",", "stream", "=", "sys", ".", "stdout", ",", "strict", "=", "False", ...
[ 473, 4 ]
[ 624, 19 ]
python
en
['en', 'error', 'th']
False
_WKBReader.read
(self, wkb)
Return a _pointer_ to C GEOS Geometry object from the given WKB.
Return a _pointer_ to C GEOS Geometry object from the given WKB.
def read(self, wkb): "Return a _pointer_ to C GEOS Geometry object from the given WKB." if isinstance(wkb, memoryview): wkb_s = bytes(wkb) return wkb_reader_read(self.ptr, wkb_s, len(wkb_s)) elif isinstance(wkb, (bytes, str)): return wkb_reader_read_hex(self.p...
[ "def", "read", "(", "self", ",", "wkb", ")", ":", "if", "isinstance", "(", "wkb", ",", "memoryview", ")", ":", "wkb_s", "=", "bytes", "(", "wkb", ")", "return", "wkb_reader_read", "(", "self", ".", "ptr", ",", "wkb_s", ",", "len", "(", "wkb_s", ")"...
[ 146, 4 ]
[ 154, 27 ]
python
en
['en', 'en', 'en']
True
WKTWriter.write
(self, geom)
Return the WKT representation of the given geometry.
Return the WKT representation of the given geometry.
def write(self, geom): "Return the WKT representation of the given geometry." return wkt_writer_write(self.ptr, geom.ptr)
[ "def", "write", "(", "self", ",", "geom", ")", ":", "return", "wkt_writer_write", "(", "self", ".", "ptr", ",", "geom", ".", "ptr", ")" ]
[ 174, 4 ]
[ 176, 51 ]
python
en
['en', 'en', 'en']
True
WKBWriter.write
(self, geom)
Return the WKB representation of the given geometry.
Return the WKB representation of the given geometry.
def write(self, geom): "Return the WKB representation of the given geometry." from django.contrib.gis.geos import Polygon geom = self._handle_empty_point(geom) wkb = wkb_writer_write(self.ptr, geom.ptr, byref(c_size_t())) if self.geos_version < (3, 6, 1) and isinstance(geom, Poly...
[ "def", "write", "(", "self", ",", "geom", ")", ":", "from", "django", ".", "contrib", ".", "gis", ".", "geos", "import", "Polygon", "geom", "=", "self", ".", "_handle_empty_point", "(", "geom", ")", "wkb", "=", "wkb_writer_write", "(", "self", ".", "pt...
[ 233, 4 ]
[ 242, 30 ]
python
en
['en', 'en', 'en']
True
WKBWriter.write_hex
(self, geom)
Return the HEXEWKB representation of the given geometry.
Return the HEXEWKB representation of the given geometry.
def write_hex(self, geom): "Return the HEXEWKB representation of the given geometry." from django.contrib.gis.geos.polygon import Polygon geom = self._handle_empty_point(geom) wkb = wkb_writer_write_hex(self.ptr, geom.ptr, byref(c_size_t())) if self.geos_version < (3, 6, 1) and i...
[ "def", "write_hex", "(", "self", ",", "geom", ")", ":", "from", "django", ".", "contrib", ".", "gis", ".", "geos", ".", "polygon", "import", "Polygon", "geom", "=", "self", ".", "_handle_empty_point", "(", "geom", ")", "wkb", "=", "wkb_writer_write_hex", ...
[ 244, 4 ]
[ 251, 18 ]
python
en
['en', 'en', 'en']
True
BaseSpatialOperations.geo_db_type
(self, f)
Return the database column type for the geometry field on the spatial backend.
Return the database column type for the geometry field on the spatial backend.
def geo_db_type(self, f): """ Return 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'", ")" ]
[ 64, 4 ]
[ 69, 108 ]
python
en
['en', 'error', 'th']
False
BaseSpatialOperations.get_distance
(self, f, value, lookup_type)
Return the distance parameters for the given geometry field, lookup value, and lookup type.
Return the distance parameters for the given geometry field, lookup value, and lookup type.
def get_distance(self, f, value, lookup_type): """ Return 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.'", ")" ]
[ 71, 4 ]
[ 76, 95 ]
python
en
['en', 'error', 'th']
False
BaseSpatialOperations.get_geom_placeholder
(self, f, value, compiler)
Return 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.
Return 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, compiler): """ Return 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", ",", "compiler", ")", ":", "def", "transform_value", "(", "value", ",", "field", ")", ":", "return", "value", "is", "not", "None", "and", "value", ".", "srid", "!=", "field", ".", "sri...
[ 78, 4 ]
[ 104, 45 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.test_stream_message_retention_days_on_stream_creation
(self)
Only admins can create streams with message_retention_days with value other than None.
Only admins can create streams with message_retention_days with value other than None.
def test_stream_message_retention_days_on_stream_creation(self) -> None: """ Only admins can create streams with message_retention_days with value other than None. """ admin = self.example_user("iago") streams_raw: List[StreamDict] = [ { "name...
[ "def", "test_stream_message_retention_days_on_stream_creation", "(", "self", ")", "->", "None", ":", "admin", "=", "self", ".", "example_user", "(", "\"iago\"", ")", "streams_raw", ":", "List", "[", "StreamDict", "]", "=", "[", "{", "\"name\"", ":", "\"new_strea...
[ 1312, 4 ]
[ 1372, 67 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.set_up_stream_for_archiving
( self, stream_name: str, invite_only: bool = False, subscribed: bool = True )
Create a stream for archiving by an administrator.
Create a stream for archiving by an administrator.
def set_up_stream_for_archiving( self, stream_name: str, invite_only: bool = False, subscribed: bool = True ) -> Stream: """ Create a stream for archiving by an administrator. """ user_profile = self.example_user("hamlet") self.login_user(user_profile) stream ...
[ "def", "set_up_stream_for_archiving", "(", "self", ",", "stream_name", ":", "str", ",", "invite_only", ":", "bool", "=", "False", ",", "subscribed", ":", "bool", "=", "True", ")", "->", "Stream", ":", "user_profile", "=", "self", ".", "example_user", "(", ...
[ 1374, 4 ]
[ 1390, 21 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.archive_stream
(self, stream: Stream)
Archive the stream and assess the result.
Archive the stream and assess the result.
def archive_stream(self, stream: Stream) -> None: """ Archive the stream and assess the result. """ active_name = stream.name realm = stream.realm stream_id = stream.id # Simulate that a stream by the same name has already been # deactivated, just to exer...
[ "def", "archive_stream", "(", "self", ",", "stream", ":", "Stream", ")", "->", "None", ":", "active_name", "=", "stream", ".", "name", "realm", "=", "stream", ".", "realm", "stream_id", "=", "stream", ".", "id", "# Simulate that a stream by the same name has alr...
[ 1392, 4 ]
[ 1445, 95 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.test_you_must_be_realm_admin
(self)
You must be on the realm to create a stream.
You must be on the realm to create a stream.
def test_you_must_be_realm_admin(self) -> None: """ You must be on the realm to create a stream. """ user_profile = self.example_user("hamlet") self.login_user(user_profile) other_realm = do_create_realm(string_id="other", name="other") stream = self.make_stream(...
[ "def", "test_you_must_be_realm_admin", "(", "self", ")", "->", "None", ":", "user_profile", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "self", ".", "login_user", "(", "user_profile", ")", "other_realm", "=", "do_create_realm", "(", "string_id", "=...
[ 1447, 4 ]
[ 1464, 59 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.test_delete_public_stream
(self)
When an administrator deletes a public stream, that stream is not visible to users at all anymore.
When an administrator deletes a public stream, that stream is not visible to users at all anymore.
def test_delete_public_stream(self) -> None: """ When an administrator deletes a public stream, that stream is not visible to users at all anymore. """ stream = self.set_up_stream_for_archiving("newstream") self.archive_stream(stream)
[ "def", "test_delete_public_stream", "(", "self", ")", "->", "None", ":", "stream", "=", "self", ".", "set_up_stream_for_archiving", "(", "\"newstream\"", ")", "self", ".", "archive_stream", "(", "stream", ")" ]
[ 1466, 4 ]
[ 1472, 35 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.test_delete_private_stream
(self)
Administrators can delete private streams they are on.
Administrators can delete private streams they are on.
def test_delete_private_stream(self) -> None: """ Administrators can delete private streams they are on. """ stream = self.set_up_stream_for_archiving("newstream", invite_only=True) self.archive_stream(stream)
[ "def", "test_delete_private_stream", "(", "self", ")", "->", "None", ":", "stream", "=", "self", ".", "set_up_stream_for_archiving", "(", "\"newstream\"", ",", "invite_only", "=", "True", ")", "self", ".", "archive_stream", "(", "stream", ")" ]
[ 1474, 4 ]
[ 1479, 35 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.test_archive_streams_youre_not_on
(self)
Administrators can delete public streams they aren't on, including private streams in their realm.
Administrators can delete public streams they aren't on, including private streams in their realm.
def test_archive_streams_youre_not_on(self) -> None: """ Administrators can delete public streams they aren't on, including private streams in their realm. """ pub_stream = self.set_up_stream_for_archiving("pubstream", subscribed=False) self.archive_stream(pub_stream) ...
[ "def", "test_archive_streams_youre_not_on", "(", "self", ")", "->", "None", ":", "pub_stream", "=", "self", ".", "set_up_stream_for_archiving", "(", "\"pubstream\"", ",", "subscribed", "=", "False", ")", "self", ".", "archive_stream", "(", "pub_stream", ")", "priv...
[ 1481, 4 ]
[ 1492, 40 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.test_cant_remove_others_from_stream
(self)
If you're not an admin, you can't remove other people from streams.
If you're not an admin, you can't remove other people from streams.
def test_cant_remove_others_from_stream(self) -> None: """ If you're not an admin, you can't remove other people from streams. """ result = self.attempt_unsubscribe_of_principal( query_count=5, target_users=[self.example_user("cordelia")], is_realm_adm...
[ "def", "test_cant_remove_others_from_stream", "(", "self", ")", "->", "None", ":", "result", "=", "self", ".", "attempt_unsubscribe_of_principal", "(", "query_count", "=", "5", ",", "target_users", "=", "[", "self", ".", "example_user", "(", "\"cordelia\"", ")", ...
[ 1568, 4 ]
[ 1581, 89 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.test_realm_admin_remove_others_from_public_stream
(self)
If you're a realm admin, you can remove people from public streams, even those you aren't on.
If you're a realm admin, you can remove people from public streams, even those you aren't on.
def test_realm_admin_remove_others_from_public_stream(self) -> None: """ If you're a realm admin, you can remove people from public streams, even those you aren't on. """ result = self.attempt_unsubscribe_of_principal( query_count=16, target_users=[self.ex...
[ "def", "test_realm_admin_remove_others_from_public_stream", "(", "self", ")", "->", "None", ":", "result", "=", "self", ".", "attempt_unsubscribe_of_principal", "(", "query_count", "=", "16", ",", "target_users", "=", "[", "self", ".", "example_user", "(", "\"cordel...
[ 1583, 4 ]
[ 1598, 53 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.test_realm_admin_remove_multiple_users_from_stream
(self)
If you're a realm admin, you can remove multiple users from a stream. TODO: We have too many queries for this situation--each additional user leads to 4 more queries. Fortunately, some of the extra work here is in do_mark_stream_messages_as_read, which gets d...
If you're a realm admin, you can remove multiple users from a stream.
def test_realm_admin_remove_multiple_users_from_stream(self) -> None: """ If you're a realm admin, you can remove multiple users from a stream. TODO: We have too many queries for this situation--each additional user leads to 4 more queries. Fortunately, some of the ...
[ "def", "test_realm_admin_remove_multiple_users_from_stream", "(", "self", ")", "->", "None", ":", "target_users", "=", "[", "self", ".", "example_user", "(", "name", ")", "for", "name", "in", "[", "\"cordelia\"", ",", "\"prospero\"", ",", "\"iago\"", ",", "\"ham...
[ 1600, 4 ]
[ 1625, 53 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.test_realm_admin_remove_others_from_subbed_private_stream
(self)
If you're a realm admin, you can remove other people from private streams you are on.
If you're a realm admin, you can remove other people from private streams you are on.
def test_realm_admin_remove_others_from_subbed_private_stream(self) -> None: """ If you're a realm admin, you can remove other people from private streams you are on. """ result = self.attempt_unsubscribe_of_principal( query_count=17, target_users=[self.ex...
[ "def", "test_realm_admin_remove_others_from_subbed_private_stream", "(", "self", ")", "->", "None", ":", "result", "=", "self", ".", "attempt_unsubscribe_of_principal", "(", "query_count", "=", "17", ",", "target_users", "=", "[", "self", ".", "example_user", "(", "...
[ 1627, 4 ]
[ 1642, 53 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.test_realm_admin_remove_others_from_unsubbed_private_stream
(self)
If you're a realm admin, you can remove people from private streams you aren't on.
If you're a realm admin, you can remove people from private streams you aren't on.
def test_realm_admin_remove_others_from_unsubbed_private_stream(self) -> None: """ If you're a realm admin, you can remove people from private streams you aren't on. """ result = self.attempt_unsubscribe_of_principal( query_count=17, target_users=[self.exa...
[ "def", "test_realm_admin_remove_others_from_unsubbed_private_stream", "(", "self", ")", "->", "None", ":", "result", "=", "self", ".", "attempt_unsubscribe_of_principal", "(", "query_count", "=", "17", ",", "target_users", "=", "[", "self", ".", "example_user", "(", ...
[ 1644, 4 ]
[ 1660, 53 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.test_stream_admin_remove_others_from_public_stream
(self)
You can remove others from public streams you're a stream administrator of.
You can remove others from public streams you're a stream administrator of.
def test_stream_admin_remove_others_from_public_stream(self) -> None: """ You can remove others from public streams you're a stream administrator of. """ result = self.attempt_unsubscribe_of_principal( query_count=16, target_users=[self.example_user("cordelia")], ...
[ "def", "test_stream_admin_remove_others_from_public_stream", "(", "self", ")", "->", "None", ":", "result", "=", "self", ".", "attempt_unsubscribe_of_principal", "(", "query_count", "=", "16", ",", "target_users", "=", "[", "self", ".", "example_user", "(", "\"corde...
[ 1662, 4 ]
[ 1677, 53 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.test_stream_admin_remove_multiple_users_from_stream
(self)
You can remove multiple users from public streams you're a stream administrator of.
You can remove multiple users from public streams you're a stream administrator of.
def test_stream_admin_remove_multiple_users_from_stream(self) -> None: """ You can remove multiple users from public streams you're a stream administrator of. """ target_users = [ self.example_user(name) for name in ["cordelia", "prospero", "othello", "hamlet", "ZOE"] ...
[ "def", "test_stream_admin_remove_multiple_users_from_stream", "(", "self", ")", "->", "None", ":", "target_users", "=", "[", "self", ".", "example_user", "(", "name", ")", "for", "name", "in", "[", "\"cordelia\"", ",", "\"prospero\"", ",", "\"othello\"", ",", "\...
[ 1679, 4 ]
[ 1698, 53 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.test_stream_admin_remove_others_from_private_stream
(self)
You can remove others from private streams you're a stream administrator of.
You can remove others from private streams you're a stream administrator of.
def test_stream_admin_remove_others_from_private_stream(self) -> None: """ You can remove others from private streams you're a stream administrator of. """ result = self.attempt_unsubscribe_of_principal( query_count=17, target_users=[self.example_user("cordelia")]...
[ "def", "test_stream_admin_remove_others_from_private_stream", "(", "self", ")", "->", "None", ":", "result", "=", "self", ".", "attempt_unsubscribe_of_principal", "(", "query_count", "=", "17", ",", "target_users", "=", "[", "self", ".", "example_user", "(", "\"cord...
[ 1700, 4 ]
[ 1715, 53 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.test_create_stream_policy_setting
(self)
When realm.create_stream_policy setting is Realm.POLICY_MEMBERS_ONLY then test that any user can create a stream. When realm.create_stream_policy setting is Realm.POLICY_ADMINS_ONLY then test that only admins can create a stream. When realm.create_stream_policy setting is Real...
When realm.create_stream_policy setting is Realm.POLICY_MEMBERS_ONLY then test that any user can create a stream.
def test_create_stream_policy_setting(self) -> None: """ When realm.create_stream_policy setting is Realm.POLICY_MEMBERS_ONLY then test that any user can create a stream. When realm.create_stream_policy setting is Realm.POLICY_ADMINS_ONLY then test that only admins can create a ...
[ "def", "test_create_stream_policy_setting", "(", "self", ")", "->", "None", ":", "user_profile", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "user_profile", ".", "date_joined", "=", "timezone_now", "(", ")", "user_profile", ".", "save", "(", ")", ...
[ 1758, 4 ]
[ 1838, 67 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.test_invite_to_stream_by_invite_period_threshold
(self)
Non admin users with account age greater or equal to the invite to stream threshold should be able to invite others to a stream.
Non admin users with account age greater or equal to the invite to stream threshold should be able to invite others to a stream.
def test_invite_to_stream_by_invite_period_threshold(self) -> None: """ Non admin users with account age greater or equal to the invite to stream threshold should be able to invite others to a stream. """ hamlet_user = self.example_user("hamlet") hamlet_user.date_joined =...
[ "def", "test_invite_to_stream_by_invite_period_threshold", "(", "self", ")", "->", "None", ":", "hamlet_user", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "hamlet_user", ".", "date_joined", "=", "timezone_now", "(", ")", "hamlet_user", ".", "save", "...
[ 1840, 4 ]
[ 1900, 9 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.test_remove_already_not_subbed
(self)
Trying to unsubscribe someone who already isn't subscribed to a stream fails gracefully.
Trying to unsubscribe someone who already isn't subscribed to a stream fails gracefully.
def test_remove_already_not_subbed(self) -> None: """ Trying to unsubscribe someone who already isn't subscribed to a stream fails gracefully. """ result = self.attempt_unsubscribe_of_principal( query_count=10, target_users=[self.example_user("cordelia")],...
[ "def", "test_remove_already_not_subbed", "(", "self", ")", "->", "None", ":", "result", "=", "self", ".", "attempt_unsubscribe_of_principal", "(", "query_count", "=", "10", ",", "target_users", "=", "[", "self", ".", "example_user", "(", "\"cordelia\"", ")", "]"...
[ 1902, 4 ]
[ 1917, 53 ]
python
en
['en', 'error', 'th']
False
StreamAdminTest.test_remove_invalid_user
(self)
Trying to unsubscribe an invalid user from a stream fails gracefully.
Trying to unsubscribe an invalid user from a stream fails gracefully.
def test_remove_invalid_user(self) -> None: """ Trying to unsubscribe an invalid user from a stream fails gracefully. """ admin = self.example_user("iago") self.login_user(admin) self.assertTrue(admin.is_realm_admin) stream_name = "hümbüǵ" self.make_strea...
[ "def", "test_remove_invalid_user", "(", "self", ")", "->", "None", ":", "admin", "=", "self", ".", "example_user", "(", "\"iago\"", ")", "self", ".", "login_user", "(", "admin", ")", "self", ".", "assertTrue", "(", "admin", ".", "is_realm_admin", ")", "str...
[ 1919, 4 ]
[ 1939, 9 ]
python
en
['en', 'error', 'th']
False
SubscriptionPropertiesTest.test_set_stream_color
(self)
A POST request to /api/v1/users/me/subscriptions/properties with stream_id and color data sets the stream color, and for that stream only. Also, make sure that any invalid hex color codes are bounced.
A POST request to /api/v1/users/me/subscriptions/properties with stream_id and color data sets the stream color, and for that stream only. Also, make sure that any invalid hex color codes are bounced.
def test_set_stream_color(self) -> None: """ A POST request to /api/v1/users/me/subscriptions/properties with stream_id and color data sets the stream color, and for that stream only. Also, make sure that any invalid hex color codes are bounced. """ test_user = self.examp...
[ "def", "test_set_stream_color", "(", "self", ")", "->", "None", ":", "test_user", "=", "self", ".", "example_user" ]
[ 2365, 4 ]
[ 2371, 37 ]
python
en
['en', 'error', 'th']
False
bulk_get_subscriber_peer_info
( realm: Realm, streams: List[Stream], )
Glossary: subscribed_ids: This shows the users who are actually subscribed to the stream, which we generally send to the person subscribing to the stream. private_peer_dict: These are the folks that need to know about a new subscriber. I...
Glossary:
def bulk_get_subscriber_peer_info( realm: Realm, streams: List[Stream], ) -> SubscriberPeerInfo: """ Glossary: subscribed_ids: This shows the users who are actually subscribed to the stream, which we generally send to the person subscribing to the stream. ...
[ "def", "bulk_get_subscriber_peer_info", "(", "realm", ":", "Realm", ",", "streams", ":", "List", "[", "Stream", "]", ",", ")", "->", "SubscriberPeerInfo", ":", "subscribed_ids", "=", "{", "}", "private_peer_dict", "=", "{", "}", "private_stream_ids", "=", "{",...
[ 136, 0 ]
[ 185, 5 ]
python
en
['en', 'error', 'th']
False
subscriber_ids_with_stream_history_access
(stream: Stream)
Returns the set of active user IDs who can access any message history on this stream (regardless of whether they have a UserMessage) based on the stream's configuration. 1. if !history_public_to_subscribers: History is not available to anyone 2. if history_public_to_subscribers and is_web_pub...
Returns the set of active user IDs who can access any message history on this stream (regardless of whether they have a UserMessage) based on the stream's configuration.
def subscriber_ids_with_stream_history_access(stream: Stream) -> Set[int]: """Returns the set of active user IDs who can access any message history on this stream (regardless of whether they have a UserMessage) based on the stream's configuration. 1. if !history_public_to_subscribers: History...
[ "def", "subscriber_ids_with_stream_history_access", "(", "stream", ":", "Stream", ")", "->", "Set", "[", "int", "]", ":", "if", "not", "stream", ".", "is_history_public_to_subscribers", "(", ")", ":", "return", "set", "(", ")", "subscriptions", "=", "get_active_...
[ 250, 0 ]
[ 279, 5 ]
python
en
['en', 'en', 'en']
True
SelectRelatedRegressTests.test_regression_7110
(self)
Regression test for bug #7110. When using select_related(), we must query the Device and Building tables using two different aliases (each) in order to differentiate the start and end Connection fields. The net result is that both the "connections = ..." queries here should giv...
Regression test for bug #7110.
def test_regression_7110(self): """ Regression test for bug #7110. When using select_related(), we must query the Device and Building tables using two different aliases (each) in order to differentiate the start and end Connection fields. The net result is that both the ...
[ "def", "test_regression_7110", "(", "self", ")", ":", "b", "=", "Building", ".", "objects", ".", "create", "(", "name", "=", "'101'", ")", "dev1", "=", "Device", ".", "objects", ".", "create", "(", "name", "=", "\"router\"", ",", "building", "=", "b", ...
[ 12, 4 ]
[ 45, 67 ]
python
en
['en', 'error', 'th']
False
SelectRelatedRegressTests.test_regression_8106
(self)
Regression test for bug #8106. Same sort of problem as the previous test, but this time there are more extra tables to pull in as part of the select_related() and some of them could potentially clash (so need to be kept separate).
Regression test for bug #8106.
def test_regression_8106(self): """ Regression test for bug #8106. Same sort of problem as the previous test, but this time there are more extra tables to pull in as part of the select_related() and some of them could potentially clash (so need to be kept separate). """ ...
[ "def", "test_regression_8106", "(", "self", ")", ":", "us", "=", "TUser", ".", "objects", ".", "create", "(", "name", "=", "\"std\"", ")", "usp", "=", "Person", ".", "objects", ".", "create", "(", "user", "=", "us", ")", "uo", "=", "TUser", ".", "o...
[ 47, 4 ]
[ 67, 67 ]
python
en
['en', 'error', 'th']
False
SelectRelatedRegressTests.test_regression_8036
(self)
Regression test for bug #8036 the first related model in the tests below ("state") is empty and we try to select the more remotely related state__country. The regression here was not skipping the empty column results for country before getting status.
Regression test for bug #8036
def test_regression_8036(self): """ Regression test for bug #8036 the first related model in the tests below ("state") is empty and we try to select the more remotely related state__country. The regression here was not skipping the empty column results for country before...
[ "def", "test_regression_8036", "(", "self", ")", ":", "Country", ".", "objects", ".", "create", "(", "name", "=", "'Australia'", ")", "active", "=", "ClientStatus", ".", "objects", ".", "create", "(", "name", "=", "'active'", ")", "client", "=", "Client", ...
[ 69, 4 ]
[ 89, 83 ]
python
en
['en', 'error', 'th']
False
SelectRelatedRegressTests.test_multi_table_inheritance
(self)
Exercising select_related() with multi-table model inheritance.
Exercising select_related() with multi-table model inheritance.
def test_multi_table_inheritance(self): """ Exercising select_related() with multi-table model inheritance. """ c1 = Child.objects.create(name="child1", value=42) Item.objects.create(name="item1", child=c1) Item.objects.create(name="item2") self.assertQuerysetEqual( ...
[ "def", "test_multi_table_inheritance", "(", "self", ")", ":", "c1", "=", "Child", ".", "objects", ".", "create", "(", "name", "=", "\"child1\"", ",", "value", "=", "42", ")", "Item", ".", "objects", ".", "create", "(", "name", "=", "\"item1\"", ",", "c...
[ 91, 4 ]
[ 100, 9 ]
python
en
['en', 'en', 'en']
True
SelectRelatedRegressTests.test_regression_12851
(self)
Regression for #12851 Deferred fields are used correctly if you select_related a subset of fields.
Regression for #12851
def test_regression_12851(self): """ Regression for #12851 Deferred fields are used correctly if you select_related a subset of fields. """ australia = Country.objects.create(name='Australia') active = ClientStatus.objects.create(name='active') wa = Stat...
[ "def", "test_regression_12851", "(", "self", ")", ":", "australia", "=", "Country", ".", "objects", ".", "create", "(", "name", "=", "'Australia'", ")", "active", "=", "ClientStatus", ".", "objects", ".", "create", "(", "name", "=", "'active'", ")", "wa", ...
[ 102, 4 ]
[ 139, 62 ]
python
en
['en', 'error', 'th']
False
fully_decorated
(request)
Expected __doc__
Expected __doc__
def fully_decorated(request): """Expected __doc__""" return HttpResponse('<html><body>dummy</body></html>')
[ "def", "fully_decorated", "(", "request", ")", ":", "return", "HttpResponse", "(", "'<html><body>dummy</body></html>'", ")" ]
[ 16, 0 ]
[ 18, 58 ]
python
en
['en', 'en', 'en']
False
DecoratorsTest.test_attributes
(self)
Tests that django decorators set certain attributes of the wrapped function.
Tests that django decorators set certain attributes of the wrapped function.
def test_attributes(self): """ Tests that django decorators set certain attributes of the wrapped function. """ self.assertEqual(fully_decorated.__name__, 'fully_decorated') self.assertEqual(fully_decorated.__doc__, 'Expected __doc__') self.assertEqual(fully_decor...
[ "def", "test_attributes", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "fully_decorated", ".", "__name__", ",", "'fully_decorated'", ")", "self", ".", "assertEqual", "(", "fully_decorated", ".", "__doc__", ",", "'Expected __doc__'", ")", "self", ".", ...
[ 74, 4 ]
[ 81, 83 ]
python
en
['en', 'error', 'th']
False
DecoratorsTest.test_user_passes_test_composition
(self)
Test that the user_passes_test decorator can be applied multiple times (#9474).
Test that the user_passes_test decorator can be applied multiple times (#9474).
def test_user_passes_test_composition(self): """ Test that the user_passes_test decorator can be applied multiple times (#9474). """ def test1(user): user.decorators_applied.append('test1') return True def test2(user): user.decorators_...
[ "def", "test_user_passes_test_composition", "(", "self", ")", ":", "def", "test1", "(", "user", ")", ":", "user", ".", "decorators_applied", ".", "append", "(", "'test1'", ")", "return", "True", "def", "test2", "(", "user", ")", ":", "user", ".", "decorato...
[ 83, 4 ]
[ 113, 54 ]
python
en
['en', 'error', 'th']
False
DecoratorsTest.test_cache_page_new_style
(self)
Test that we can call cache_page the new way
Test that we can call cache_page the new way
def test_cache_page_new_style(self): """ Test that we can call cache_page the new way """ def my_view(request): return "response" my_view_cached = cache_page(123)(my_view) self.assertEqual(my_view_cached(HttpRequest()), "response") my_view_cached2 = ca...
[ "def", "test_cache_page_new_style", "(", "self", ")", ":", "def", "my_view", "(", "request", ")", ":", "return", "\"response\"", "my_view_cached", "=", "cache_page", "(", "123", ")", "(", "my_view", ")", "self", ".", "assertEqual", "(", "my_view_cached", "(", ...
[ 115, 4 ]
[ 124, 68 ]
python
en
['en', 'error', 'th']
False
DecoratorsTest.test_require_safe_accepts_only_safe_methods
(self)
Test for the require_safe decorator. A view returns either a response or an exception. Refs #15637.
Test for the require_safe decorator. A view returns either a response or an exception. Refs #15637.
def test_require_safe_accepts_only_safe_methods(self): """ Test for the require_safe decorator. A view returns either a response or an exception. Refs #15637. """ def my_view(request): return HttpResponse("OK") my_safe_view = require_safe(my_view) ...
[ "def", "test_require_safe_accepts_only_safe_methods", "(", "self", ")", ":", "def", "my_view", "(", "request", ")", ":", "return", "HttpResponse", "(", "\"OK\"", ")", "my_safe_view", "=", "require_safe", "(", "my_view", ")", "request", "=", "HttpRequest", "(", "...
[ 126, 4 ]
[ 145, 76 ]
python
en
['en', 'error', 'th']
False
XFrameOptionsDecoratorsTests.test_deny_decorator
(self)
Ensures @xframe_options_deny properly sets the X-Frame-Options header.
Ensures
def test_deny_decorator(self): """ Ensures @xframe_options_deny properly sets the X-Frame-Options header. """ @xframe_options_deny def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual(r['X-Frame-Options'], 'DENY')
[ "def", "test_deny_decorator", "(", "self", ")", ":", "@", "xframe_options_deny", "def", "a_view", "(", "request", ")", ":", "return", "HttpResponse", "(", ")", "r", "=", "a_view", "(", "HttpRequest", "(", ")", ")", "self", ".", "assertEqual", "(", "r", "...
[ 278, 4 ]
[ 286, 54 ]
python
en
['en', 'error', 'th']
False
XFrameOptionsDecoratorsTests.test_sameorigin_decorator
(self)
Ensures @xframe_options_sameorigin properly sets the X-Frame-Options header.
Ensures
def test_sameorigin_decorator(self): """ Ensures @xframe_options_sameorigin properly sets the X-Frame-Options header. """ @xframe_options_sameorigin def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual(r['X-Fram...
[ "def", "test_sameorigin_decorator", "(", "self", ")", ":", "@", "xframe_options_sameorigin", "def", "a_view", "(", "request", ")", ":", "return", "HttpResponse", "(", ")", "r", "=", "a_view", "(", "HttpRequest", "(", ")", ")", "self", ".", "assertEqual", "("...
[ 288, 4 ]
[ 297, 60 ]
python
en
['en', 'error', 'th']
False
XFrameOptionsDecoratorsTests.test_exempt_decorator
(self)
Ensures @xframe_options_exempt properly instructs the XFrameOptionsMiddleware to NOT set the header.
Ensures
def test_exempt_decorator(self): """ Ensures @xframe_options_exempt properly instructs the XFrameOptionsMiddleware to NOT set the header. """ @xframe_options_exempt def a_view(request): return HttpResponse() req = HttpRequest() resp = a_view(re...
[ "def", "test_exempt_decorator", "(", "self", ")", ":", "@", "xframe_options_exempt", "def", "a_view", "(", "request", ")", ":", "return", "HttpResponse", "(", ")", "req", "=", "HttpRequest", "(", ")", "resp", "=", "a_view", "(", "req", ")", "self", ".", ...
[ 299, 4 ]
[ 315, 62 ]
python
en
['en', 'error', 'th']
False
get_list_of_data_points_to_plot
(exp_dir, all_datapoints_including_nonMIRC=True)
Create and return a list of paths to those directories whose data should be plotted. Only those data points that have a MIRC will be plotted. Args: exp_dir: path to directory w/ experiment all_datapoints_including_nonMIRC: flag to determine whether all datapoints sh...
Create and return a list of paths to those directories whose data should be plotted. Only those data points that have a MIRC will be plotted.
def get_list_of_data_points_to_plot(exp_dir, all_datapoints_including_nonMIRC=True): """Create and return a list of paths to those directories whose data should be plotted. Only those data points that have a MIRC will be plotted. Args: exp_dir: ...
[ "def", "get_list_of_data_points_to_plot", "(", "exp_dir", ",", "all_datapoints_including_nonMIRC", "=", "True", ")", ":", "list_all_files_in_exp_dir", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "exp_dir", ",", "\"*\"", ")", ")", "data_po...
[ 10, 0 ]
[ 55, 34 ]
python
en
['en', 'en', 'en']
True
get_img_class_dict_all_data
( data_point_to_plot_list, exp_dir, img_identifier)
obtain all data for one datapoint, and save all this data into an ordered dictionary. Args: data_point_to_plot_list: list of data points to plot exp_dir: path to experiment directory img_identifier: string describing the datapoint, e.g. 'plane_INclass404' Retur...
obtain all data for one datapoint, and save all this data into an ordered dictionary.
def get_img_class_dict_all_data( data_point_to_plot_list, exp_dir, img_identifier): """obtain all data for one datapoint, and save all this data into an ordered dictionary. Args: data_point_to_plot_list: list of data points to plot exp_dir: path to experi...
[ "def", "get_img_class_dict_all_data", "(", "data_point_to_plot_list", ",", "exp_dir", ",", "img_identifier", ")", ":", "# list of paths to all npz files", "npz_files_list", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "exp_dir", ",", "img_iden...
[ 64, 0 ]
[ 103, 25 ]
python
en
['en', 'en', 'en']
True
CheckSessionCookieSecureTest.test_session_cookie_secure_with_installed_app
(self)
Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions" is in INSTALLED_APPS.
Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions" is in INSTALLED_APPS.
def test_session_cookie_secure_with_installed_app(self): """ Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions" is in INSTALLED_APPS. """ self.assertEqual(self.func(None), [sessions.W010])
[ "def", "test_session_cookie_secure_with_installed_app", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "sessions", ".", "W010", "]", ")" ]
[ 19, 4 ]
[ 24, 58 ]
python
en
['en', 'error', 'th']
False
CheckSessionCookieSecureTest.test_session_cookie_secure_with_middleware
(self)
Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions.middleware.SessionMiddleware" is in MIDDLEWARE_CLASSES.
Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions.middleware.SessionMiddleware" is in MIDDLEWARE_CLASSES.
def test_session_cookie_secure_with_middleware(self): """ Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions.middleware.SessionMiddleware" is in MIDDLEWARE_CLASSES. """ self.assertEqual(self.func(None), [sessions.W011])
[ "def", "test_session_cookie_secure_with_middleware", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "sessions", ".", "W011", "]", ")" ]
[ 30, 4 ]
[ 36, 58 ]
python
en
['en', 'error', 'th']
False
CheckSessionCookieSecureTest.test_session_cookie_secure_both
(self)
If SESSION_COOKIE_SECURE is off and we find both the session app and the middleware, provide one common warning.
If SESSION_COOKIE_SECURE is off and we find both the session app and the middleware, provide one common warning.
def test_session_cookie_secure_both(self): """ If SESSION_COOKIE_SECURE is off and we find both the session app and the middleware, provide one common warning. """ self.assertEqual(self.func(None), [sessions.W012])
[ "def", "test_session_cookie_secure_both", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "sessions", ".", "W012", "]", ")" ]
[ 42, 4 ]
[ 47, 58 ]
python
en
['en', 'error', 'th']
False
CheckSessionCookieSecureTest.test_session_cookie_secure_true
(self)
If SESSION_COOKIE_SECURE is on, there's no warning about it.
If SESSION_COOKIE_SECURE is on, there's no warning about it.
def test_session_cookie_secure_true(self): """ If SESSION_COOKIE_SECURE is on, there's no warning about it. """ self.assertEqual(self.func(None), [])
[ "def", "test_session_cookie_secure_true", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "]", ")" ]
[ 53, 4 ]
[ 57, 45 ]
python
en
['en', 'error', 'th']
False
CheckSessionCookieHttpOnlyTest.test_session_cookie_httponly_with_installed_app
(self)
Warn if SESSION_COOKIE_HTTPONLY is off and "django.contrib.sessions" is in INSTALLED_APPS.
Warn if SESSION_COOKIE_HTTPONLY is off and "django.contrib.sessions" is in INSTALLED_APPS.
def test_session_cookie_httponly_with_installed_app(self): """ Warn if SESSION_COOKIE_HTTPONLY is off and "django.contrib.sessions" is in INSTALLED_APPS. """ self.assertEqual(self.func(None), [sessions.W013])
[ "def", "test_session_cookie_httponly_with_installed_app", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "sessions", ".", "W013", "]", ")" ]
[ 70, 4 ]
[ 75, 58 ]
python
en
['en', 'error', 'th']
False
CheckSessionCookieHttpOnlyTest.test_session_cookie_httponly_with_middleware
(self)
Warn if SESSION_COOKIE_HTTPONLY is off and "django.contrib.sessions.middleware.SessionMiddleware" is in MIDDLEWARE_CLASSES.
Warn if SESSION_COOKIE_HTTPONLY is off and "django.contrib.sessions.middleware.SessionMiddleware" is in MIDDLEWARE_CLASSES.
def test_session_cookie_httponly_with_middleware(self): """ Warn if SESSION_COOKIE_HTTPONLY is off and "django.contrib.sessions.middleware.SessionMiddleware" is in MIDDLEWARE_CLASSES. """ self.assertEqual(self.func(None), [sessions.W014])
[ "def", "test_session_cookie_httponly_with_middleware", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "sessions", ".", "W014", "]", ")" ]
[ 81, 4 ]
[ 87, 58 ]
python
en
['en', 'error', 'th']
False
CheckSessionCookieHttpOnlyTest.test_session_cookie_httponly_both
(self)
If SESSION_COOKIE_HTTPONLY is off and we find both the session app and the middleware, provide one common warning.
If SESSION_COOKIE_HTTPONLY is off and we find both the session app and the middleware, provide one common warning.
def test_session_cookie_httponly_both(self): """ If SESSION_COOKIE_HTTPONLY is off and we find both the session app and the middleware, provide one common warning. """ self.assertEqual(self.func(None), [sessions.W015])
[ "def", "test_session_cookie_httponly_both", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "self", ".", "func", "(", "None", ")", ",", "[", "sessions", ".", "W015", "]", ")" ]
[ 93, 4 ]
[ 98, 58 ]
python
en
['en', 'error', 'th']
False