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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
filter_autoscaled_stopped_instance_candidates | (self, caller, expected_instance_count, target_for_dispatch=None) | Return a list of startable instances (in the autoscaled fleet).
Filter and sort instance candidates to be started in 'scale up' event in the Main subfleet.
:param caller: The name of the module algorithm requesting a scaleout.
:param expected_instance_count: The absolute numb... | Return a list of startable instances (in the autoscaled fleet). | def filter_autoscaled_stopped_instance_candidates(self, caller, expected_instance_count, target_for_dispatch=None):
""" Return a list of startable instances (in the autoscaled fleet).
Filter and sort instance candidates to be started in 'scale up' event in the Main subfleet.
:param caller: ... | [
"def",
"filter_autoscaled_stopped_instance_candidates",
"(",
"self",
",",
"caller",
",",
"expected_instance_count",
",",
"target_for_dispatch",
"=",
"None",
")",
":",
"disabled_azs",
"=",
"self",
".",
"get_disabled_azs",
"(",
")",
"active_instances",
"=",
"self",
".",... | [
1150,
4
] | [
1172,
32
] | python | en | ['en', 'en', 'en'] | True |
filter_running_instance_candidates | (self, active_instances) | Return a list of stoppable instances in the autoscaled fleet.
:param active_instances: List of running instances to filter and sort as candidates for stop
:return A list of stoppable instances
| Return a list of stoppable instances in the autoscaled fleet. | def filter_running_instance_candidates(self, active_instances):
""" Return a list of stoppable instances in the autoscaled fleet.
:param active_instances: List of running instances to filter and sort as candidates for stop
:return A list of stoppable instances
"""
# Filter out i... | [
"def",
"filter_running_instance_candidates",
"(",
"self",
",",
"active_instances",
")",
":",
"# Filter out instances that are not stoppable",
"active_instances",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"i",
":",
"i",
"[",
"\"InstanceId\"",
"]",
"not",
"in",
"self",... | [
1174,
4
] | [
1197,
31
] | python | en | ['en', 'en', 'en'] | True |
instance_action | (self, desired_instance_count, caller, reject_if_initial_in_progress=False, target_for_dispatch=None) | Perform action (start or stop instances) needed to achieve specified 'desired_instance_count' in the Main fleet.
:param desired_instance_count: The absolute number of instances expected to be serving.
:param caller: The name of the algorithm asking for a change in the... | Perform action (start or stop instances) needed to achieve specified 'desired_instance_count' in the Main fleet. | def instance_action(self, desired_instance_count, caller, reject_if_initial_in_progress=False, target_for_dispatch=None):
""" Perform action (start or stop instances) needed to achieve specified 'desired_instance_count' in the Main fleet.
:param desired_instance_count: The absolute number of i... | [
"def",
"instance_action",
"(",
"self",
",",
"desired_instance_count",
",",
"caller",
",",
"reject_if_initial_in_progress",
"=",
"False",
",",
"target_for_dispatch",
"=",
"None",
")",
":",
"now",
"=",
"self",
".",
"context",
"[",
"\"now\"",
"]",
"min_instance_count... | [
1201,
4
] | [
1281,
19
] | python | en | ['en', 'en', 'en'] | True |
is_instance_cpu_crediting_eligible | (self, i) | Return a boolean if the specified instance is eligible to the CPU Crediting mechanism.
| Return a boolean if the specified instance is eligible to the CPU Crediting mechanism.
| def is_instance_cpu_crediting_eligible(self, i):
""" Return a boolean if the specified instance is eligible to the CPU Crediting mechanism.
"""
instance_type = i["InstanceType"]
if instance_type not in self.cpu_credits or instance_type.startswith("t2"):
return False # Not a b... | [
"def",
"is_instance_cpu_crediting_eligible",
"(",
"self",
",",
"i",
")",
":",
"instance_type",
"=",
"i",
"[",
"\"InstanceType\"",
"]",
"if",
"instance_type",
"not",
"in",
"self",
".",
"cpu_credits",
"or",
"instance_type",
".",
"startswith",
"(",
"\"t2\"",
")",
... | [
1286,
4
] | [
1292,
19
] | python | en | ['en', 'en', 'en'] | True |
is_instance_need_cpu_crediting | (self, i, meta) | Return True if the specified instance need CPU Crediting.
:param i: An instance structure
:param meta: If not 'None', a dict populated with Metadata
:return True if the specified instance need CPU Crediting.:w
| Return True if the specified instance need CPU Crediting. | def is_instance_need_cpu_crediting(self, i, meta):
""" Return True if the specified instance need CPU Crediting.
:param i: An instance structure
:param meta: If not 'None', a dict populated with Metadata
:return True if the specified instance need CPU Crediting.:w
"""
... | [
"def",
"is_instance_need_cpu_crediting",
"(",
"self",
",",
"i",
",",
"meta",
")",
":",
"now",
"=",
"self",
".",
"context",
"[",
"\"now\"",
"]",
"instance_id",
"=",
"i",
"[",
"\"InstanceId\"",
"]",
"instance_type",
"=",
"i",
"[",
"\"InstanceType\"",
"]",
"i... | [
1294,
4
] | [
1337,
19
] | python | en | ['en', 'en', 'en'] | True |
stop_drained_instances | (self) | Method responsible to stop instance marked as 'draining'.
| Method responsible to stop instance marked as 'draining'.
| def stop_drained_instances(self):
""" Method responsible to stop instance marked as 'draining'.
"""
now = self.context["now"]
cw = self.cloudwatch
draining_target_instance_ids = self.targetgroup.get_registered_instance_ids(state="draining")
if ... | [
"def",
"stop_drained_instances",
"(",
"self",
")",
":",
"now",
"=",
"self",
".",
"context",
"[",
"\"now\"",
"]",
"cw",
"=",
"self",
".",
"cloudwatch",
"draining_target_instance_ids",
"=",
"self",
".",
"targetgroup",
".",
"get_registered_instance_ids",
"(",
"stat... | [
1373,
4
] | [
1498,
45
] | python | en | ['en', 'en', 'en'] | True |
wakeup_burstable_instances | (self) | Start burstable instances that are stopped for a long time and could lose their CPU Credits soon (near one week stopped).
| Start burstable instances that are stopped for a long time and could lose their CPU Credits soon (near one week stopped).
| def wakeup_burstable_instances(self):
""" Start burstable instances that are stopped for a long time and could lose their CPU Credits soon (near one week stopped).
"""
if not Cfg.get_int("ec2.schedule.burstable_instance.preserve_accrued_cpu_credit"):
log.log(log.NOTICE, "Burstable in... | [
"def",
"wakeup_burstable_instances",
"(",
"self",
")",
":",
"if",
"not",
"Cfg",
".",
"get_int",
"(",
"\"ec2.schedule.burstable_instance.preserve_accrued_cpu_credit\"",
")",
":",
"log",
".",
"log",
"(",
"log",
".",
"NOTICE",
",",
"\"Burstable instance CPU Credit preserva... | [
1500,
4
] | [
1519,
49
] | python | en | ['en', 'en', 'en'] | True |
subfleet_action | (self, subfleet, delta) | Method responsable to change the amount of running instances is a subfleet.
It is similar to instance_action() but to manage subfleet instance count.
The method is responsible to start/stop instances based on vertical scaling policy and instance conditions ('initializing', too young etc...)
:... | Method responsable to change the amount of running instances is a subfleet. | def subfleet_action(self, subfleet, delta):
""" Method responsable to change the amount of running instances is a subfleet.
It is similar to instance_action() but to manage subfleet instance count.
The method is responsible to start/stop instances based on vertical scaling policy and instance c... | [
"def",
"subfleet_action",
"(",
"self",
",",
"subfleet",
",",
"delta",
")",
":",
"def",
"_verticalscale_sort_and_warn",
"(",
"subfleet",
",",
"candidates",
",",
"reverse",
"=",
"False",
")",
":",
"\"\"\" Take into account vertical scaling policy if it exists for the subfle... | [
1521,
4
] | [
1618,
59
] | python | en | ['en', 'en', 'en'] | True |
CustomTestClientTest.test_custom_test_client | (self) | A test case can specify a custom class for self.client. | A test case can specify a custom class for self.client. | def test_custom_test_client(self):
"""A test case can specify a custom class for self.client."""
self.assertEqual(hasattr(self.client, "i_am_customized"), True) | [
"def",
"test_custom_test_client",
"(",
"self",
")",
":",
"self",
".",
"assertEqual",
"(",
"hasattr",
"(",
"self",
".",
"client",
",",
"\"i_am_customized\"",
")",
",",
"True",
")"
] | [
549,
4
] | [
551,
71
] | python | en | ['en', 'en', 'en'] | True |
last_arg_byref | (args) | Returns the last C argument's value by reference. | Returns the last C argument's value by reference. | def last_arg_byref(args):
"Returns the last C argument's value by reference."
return args[-1]._obj.value | [
"def",
"last_arg_byref",
"(",
"args",
")",
":",
"return",
"args",
"[",
"-",
"1",
"]",
".",
"_obj",
".",
"value"
] | [
16,
0
] | [
18,
30
] | python | en | ['en', 'en', 'en'] | True |
check_dbl | (result, func, cargs) | Checks the status code and returns the double value passed in by reference. | Checks the status code and returns the double value passed in by reference. | def check_dbl(result, func, cargs):
"Checks the status code and returns the double value passed in by reference."
# Checking the status code
if result != 1:
return None
# Double passed in by reference, return its value.
return last_arg_byref(cargs) | [
"def",
"check_dbl",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"# Checking the status code",
"if",
"result",
"!=",
"1",
":",
"return",
"None",
"# Double passed in by reference, return its value.",
"return",
"last_arg_byref",
"(",
"cargs",
")"
] | [
21,
0
] | [
27,
32
] | python | en | ['en', 'en', 'en'] | True |
check_geom | (result, func, cargs) | Error checking on routines that return Geometries. | Error checking on routines that return Geometries. | def check_geom(result, func, cargs):
"Error checking on routines that return Geometries."
if not result:
raise GEOSException('Error encountered checking Geometry returned from GEOS C function "%s".' % func.__name__)
return result | [
"def",
"check_geom",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"if",
"not",
"result",
":",
"raise",
"GEOSException",
"(",
"'Error encountered checking Geometry returned from GEOS C function \"%s\".'",
"%",
"func",
".",
"__name__",
")",
"return",
"result"
] | [
30,
0
] | [
34,
17
] | python | en | ['en', 'el-Latn', 'en'] | True |
check_minus_one | (result, func, cargs) | Error checking on routines that should not return -1. | Error checking on routines that should not return -1. | def check_minus_one(result, func, cargs):
"Error checking on routines that should not return -1."
if result == -1:
raise GEOSException('Error encountered in GEOS C function "%s".' % func.__name__)
else:
return result | [
"def",
"check_minus_one",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"if",
"result",
"==",
"-",
"1",
":",
"raise",
"GEOSException",
"(",
"'Error encountered in GEOS C function \"%s\".'",
"%",
"func",
".",
"__name__",
")",
"else",
":",
"return",
"resul... | [
37,
0
] | [
42,
21
] | python | en | ['en', 'en', 'en'] | True |
check_predicate | (result, func, cargs) | Error checking for unary/binary predicate functions. | Error checking for unary/binary predicate functions. | def check_predicate(result, func, cargs):
"Error checking for unary/binary predicate functions."
val = ord(result) # getting the ordinal from the character
if val == 1:
return True
elif val == 0:
return False
else:
raise GEOSException('Error encountered on GEOS C predicate f... | [
"def",
"check_predicate",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"val",
"=",
"ord",
"(",
"result",
")",
"# getting the ordinal from the character",
"if",
"val",
"==",
"1",
":",
"return",
"True",
"elif",
"val",
"==",
"0",
":",
"return",
"False"... | [
45,
0
] | [
53,
99
] | python | en | ['en', 'en', 'en'] | True |
check_sized_string | (result, func, cargs) |
Error checking for routines that return explicitly sized strings.
This frees the memory allocated by GEOS at the result pointer.
|
Error checking for routines that return explicitly sized strings. | def check_sized_string(result, func, cargs):
"""
Error checking for routines that return explicitly sized strings.
This frees the memory allocated by GEOS at the result pointer.
"""
if not result:
raise GEOSException('Invalid string pointer returned by GEOS C function "%s"' % func.__name__)... | [
"def",
"check_sized_string",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"if",
"not",
"result",
":",
"raise",
"GEOSException",
"(",
"'Invalid string pointer returned by GEOS C function \"%s\"'",
"%",
"func",
".",
"__name__",
")",
"# A c_size_t object is passed i... | [
56,
0
] | [
70,
12
] | python | en | ['en', 'error', 'th'] | False |
check_string | (result, func, cargs) |
Error checking for routines that return strings.
This frees the memory allocated by GEOS at the result pointer.
|
Error checking for routines that return strings. | def check_string(result, func, cargs):
"""
Error checking for routines that return strings.
This frees the memory allocated by GEOS at the result pointer.
"""
if not result:
raise GEOSException('Error encountered checking string return value in GEOS C function "%s".' % func.__name__)
# ... | [
"def",
"check_string",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"if",
"not",
"result",
":",
"raise",
"GEOSException",
"(",
"'Error encountered checking string return value in GEOS C function \"%s\".'",
"%",
"func",
".",
"__name__",
")",
"# Getting the string ... | [
73,
0
] | [
85,
12
] | python | en | ['en', 'error', 'th'] | False |
check_zero | (result, func, cargs) | Error checking on routines that should not return 0. | Error checking on routines that should not return 0. | def check_zero(result, func, cargs):
"Error checking on routines that should not return 0."
if result == 0:
raise GEOSException('Error encountered in GEOS C function "%s".' % func.__name__)
else:
return result | [
"def",
"check_zero",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"if",
"result",
"==",
"0",
":",
"raise",
"GEOSException",
"(",
"'Error encountered in GEOS C function \"%s\".'",
"%",
"func",
".",
"__name__",
")",
"else",
":",
"return",
"result"
] | [
88,
0
] | [
93,
21
] | python | en | ['en', 'en', 'en'] | True |
upload_docs._build_multipart | (cls, data) |
Build up the MIME payload for the POST data
|
Build up the MIME payload for the POST data
| def _build_multipart(cls, data):
"""
Build up the MIME payload for the POST data
"""
boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
sep_boundary = b'\n--' + boundary.encode('ascii')
end_boundary = sep_boundary + b'--'
end_items = end_boundary, b"... | [
"def",
"_build_multipart",
"(",
"cls",
",",
"data",
")",
":",
"boundary",
"=",
"'--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'",
"sep_boundary",
"=",
"b'\\n--'",
"+",
"boundary",
".",
"encode",
"(",
"'ascii'",
")",
"end_boundary",
"=",
"sep_boundary",
"+",
"b... | [
125,
4
] | [
141,
49
] | python | en | ['en', 'error', 'th'] | False |
handle_default_options | (options) |
Include any default options that all commands should accept here
so that ManagementUtility can handle them before searching for
user commands.
|
Include any default options that all commands should accept here
so that ManagementUtility can handle them before searching for
user commands.
| def handle_default_options(options):
"""
Include any default options that all commands should accept here
so that ManagementUtility can handle them before searching for
user commands.
"""
if options.settings:
os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
if options.pythonpa... | [
"def",
"handle_default_options",
"(",
"options",
")",
":",
"if",
"options",
".",
"settings",
":",
"os",
".",
"environ",
"[",
"'DJANGO_SETTINGS_MODULE'",
"]",
"=",
"options",
".",
"settings",
"if",
"options",
".",
"pythonpath",
":",
"sys",
".",
"path",
".",
... | [
63,
0
] | [
72,
46
] | python | en | ['en', 'error', 'th'] | False |
no_translations | (handle_func) | Decorator that forces a command to run with translations deactivated. | Decorator that forces a command to run with translations deactivated. | def no_translations(handle_func):
"""Decorator that forces a command to run with translations deactivated."""
def wrapped(*args, **kwargs):
from django.utils import translation
saved_locale = translation.get_language()
translation.deactivate_all()
try:
res = handle_fu... | [
"def",
"no_translations",
"(",
"handle_func",
")",
":",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"django",
".",
"utils",
"import",
"translation",
"saved_locale",
"=",
"translation",
".",
"get_language",
"(",
")",
"tran... | [
75,
0
] | [
87,
18
] | python | en | ['en', 'en', 'en'] | True |
BaseCommand.get_version | (self) |
Return the Django version, which should be correct for all built-in
Django commands. User-supplied commands can override this method to
return their own version.
|
Return the Django version, which should be correct for all built-in
Django commands. User-supplied commands can override this method to
return their own version.
| def get_version(self):
"""
Return the Django version, which should be correct for all built-in
Django commands. User-supplied commands can override this method to
return their own version.
"""
return django.get_version() | [
"def",
"get_version",
"(",
"self",
")",
":",
"return",
"django",
".",
"get_version",
"(",
")"
] | [
240,
4
] | [
246,
35
] | python | en | ['en', 'error', 'th'] | False |
BaseCommand.create_parser | (self, prog_name, subcommand, **kwargs) |
Create and return the ``ArgumentParser`` which will be used to
parse the arguments to this command.
|
Create and return the ``ArgumentParser`` which will be used to
parse the arguments to this command.
| def create_parser(self, prog_name, subcommand, **kwargs):
"""
Create and return the ``ArgumentParser`` which will be used to
parse the arguments to this command.
"""
parser = CommandParser(
prog='%s %s' % (os.path.basename(prog_name), subcommand),
descript... | [
"def",
"create_parser",
"(",
"self",
",",
"prog_name",
",",
"subcommand",
",",
"*",
"*",
"kwargs",
")",
":",
"parser",
"=",
"CommandParser",
"(",
"prog",
"=",
"'%s %s'",
"%",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"prog_name",
")",
",",
"subcomm... | [
248,
4
] | [
294,
21
] | python | en | ['en', 'error', 'th'] | False |
BaseCommand.add_arguments | (self, parser) |
Entry point for subclassed commands to add custom arguments.
|
Entry point for subclassed commands to add custom arguments.
| def add_arguments(self, parser):
"""
Entry point for subclassed commands to add custom arguments.
"""
pass | [
"def",
"add_arguments",
"(",
"self",
",",
"parser",
")",
":",
"pass"
] | [
296,
4
] | [
300,
12
] | python | en | ['en', 'error', 'th'] | False |
BaseCommand.print_help | (self, prog_name, subcommand) |
Print the help message for this command, derived from
``self.usage()``.
|
Print the help message for this command, derived from
``self.usage()``.
| def print_help(self, prog_name, subcommand):
"""
Print the help message for this command, derived from
``self.usage()``.
"""
parser = self.create_parser(prog_name, subcommand)
parser.print_help() | [
"def",
"print_help",
"(",
"self",
",",
"prog_name",
",",
"subcommand",
")",
":",
"parser",
"=",
"self",
".",
"create_parser",
"(",
"prog_name",
",",
"subcommand",
")",
"parser",
".",
"print_help",
"(",
")"
] | [
302,
4
] | [
308,
27
] | python | en | ['en', 'error', 'th'] | False |
BaseCommand.run_from_argv | (self, argv) |
Set up any environment changes requested (e.g., Python path
and Django settings), then run this command. If the
command raises a ``CommandError``, intercept it and print it sensibly
to stderr. If the ``--traceback`` option is present or the raised
``Exception`` is not ``CommandE... |
Set up any environment changes requested (e.g., Python path
and Django settings), then run this command. If the
command raises a ``CommandError``, intercept it and print it sensibly
to stderr. If the ``--traceback`` option is present or the raised
``Exception`` is not ``CommandE... | def run_from_argv(self, argv):
"""
Set up any environment changes requested (e.g., Python path
and Django settings), then run this command. If the
command raises a ``CommandError``, intercept it and print it sensibly
to stderr. If the ``--traceback`` option is present or the rais... | [
"def",
"run_from_argv",
"(",
"self",
",",
"argv",
")",
":",
"self",
".",
"_called_from_command_line",
"=",
"True",
"parser",
"=",
"self",
".",
"create_parser",
"(",
"argv",
"[",
"0",
"]",
",",
"argv",
"[",
"1",
"]",
")",
"options",
"=",
"parser",
".",
... | [
310,
4
] | [
344,
20
] | python | en | ['en', 'error', 'th'] | False |
BaseCommand.execute | (self, *args, **options) |
Try to execute this command, performing system checks if needed (as
controlled by the ``requires_system_checks`` attribute, except if
force-skipped).
|
Try to execute this command, performing system checks if needed (as
controlled by the ``requires_system_checks`` attribute, except if
force-skipped).
| def execute(self, *args, **options):
"""
Try to execute this command, performing system checks if needed (as
controlled by the ``requires_system_checks`` attribute, except if
force-skipped).
"""
if options['force_color'] and options['no_color']:
raise CommandE... | [
"def",
"execute",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"if",
"options",
"[",
"'force_color'",
"]",
"and",
"options",
"[",
"'no_color'",
"]",
":",
"raise",
"CommandError",
"(",
"\"The --no-color and --force-color options can't be use... | [
346,
4
] | [
378,
21
] | python | en | ['en', 'error', 'th'] | False |
BaseCommand.check | (self, app_configs=None, tags=None, display_num_errors=False,
include_deployment_checks=False, fail_level=checks.ERROR) |
Use the system check framework to validate entire Django project.
Raise CommandError for any serious message (error or critical errors).
If there are only light messages (like warnings), print them to stderr
and don't raise an exception.
|
Use the system check framework to validate entire Django project.
Raise CommandError for any serious message (error or critical errors).
If there are only light messages (like warnings), print them to stderr
and don't raise an exception.
| def check(self, app_configs=None, tags=None, display_num_errors=False,
include_deployment_checks=False, fail_level=checks.ERROR):
"""
Use the system check framework to validate entire Django project.
Raise CommandError for any serious message (error or critical errors).
If ... | [
"def",
"check",
"(",
"self",
",",
"app_configs",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"display_num_errors",
"=",
"False",
",",
"include_deployment_checks",
"=",
"False",
",",
"fail_level",
"=",
"checks",
".",
"ERROR",
")",
":",
"all_issues",
"=",
"s... | [
383,
4
] | [
448,
38
] | python | en | ['en', 'error', 'th'] | False |
BaseCommand.check_migrations | (self) |
Print a warning if the set of migrations on disk don't match the
migrations in the database.
|
Print a warning if the set of migrations on disk don't match the
migrations in the database.
| def check_migrations(self):
"""
Print a warning if the set of migrations on disk don't match the
migrations in the database.
"""
from django.db.migrations.executor import MigrationExecutor
try:
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
... | [
"def",
"check_migrations",
"(",
"self",
")",
":",
"from",
"django",
".",
"db",
".",
"migrations",
".",
"executor",
"import",
"MigrationExecutor",
"try",
":",
"executor",
"=",
"MigrationExecutor",
"(",
"connections",
"[",
"DEFAULT_DB_ALIAS",
"]",
")",
"except",
... | [
450,
4
] | [
475,
99
] | python | en | ['en', 'error', 'th'] | False |
BaseCommand.handle | (self, *args, **options) |
The actual logic of the command. Subclasses must implement
this method.
|
The actual logic of the command. Subclasses must implement
this method.
| def handle(self, *args, **options):
"""
The actual logic of the command. Subclasses must implement
this method.
"""
raise NotImplementedError('subclasses of BaseCommand must provide a handle() method') | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseCommand must provide a handle() method'",
")"
] | [
477,
4
] | [
482,
93
] | python | en | ['en', 'error', 'th'] | False |
AppCommand.handle_app_config | (self, app_config, **options) |
Perform the command's actions for app_config, an AppConfig instance
corresponding to an application label given on the command line.
|
Perform the command's actions for app_config, an AppConfig instance
corresponding to an application label given on the command line.
| def handle_app_config(self, app_config, **options):
"""
Perform the command's actions for app_config, an AppConfig instance
corresponding to an application label given on the command line.
"""
raise NotImplementedError(
"Subclasses of AppCommand must provide"
... | [
"def",
"handle_app_config",
"(",
"self",
",",
"app_config",
",",
"*",
"*",
"options",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Subclasses of AppCommand must provide\"",
"\"a handle_app_config() method.\"",
")"
] | [
511,
4
] | [
518,
44
] | python | en | ['en', 'error', 'th'] | False |
LabelCommand.handle_label | (self, label, **options) |
Perform the command's actions for ``label``, which will be the
string as given on the command line.
|
Perform the command's actions for ``label``, which will be the
string as given on the command line.
| def handle_label(self, label, **options):
"""
Perform the command's actions for ``label``, which will be the
string as given on the command line.
"""
raise NotImplementedError('subclasses of LabelCommand must provide a handle_label() method') | [
"def",
"handle_label",
"(",
"self",
",",
"label",
",",
"*",
"*",
"options",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of LabelCommand must provide a handle_label() method'",
")"
] | [
547,
4
] | [
552,
100
] | python | en | ['en', 'error', 'th'] | False |
capfirst | (x) | Capitalize the first letter of a string. | Capitalize the first letter of a string. | def capfirst(x):
"""Capitalize the first letter of a string."""
return x and str(x)[0].upper() + str(x)[1:] | [
"def",
"capfirst",
"(",
"x",
")",
":",
"return",
"x",
"and",
"str",
"(",
"x",
")",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"str",
"(",
"x",
")",
"[",
"1",
":",
"]"
] | [
13,
0
] | [
15,
47
] | python | en | ['en', 'en', 'en'] | True |
wrap | (text, width) |
A word-wrap function that preserves existing line breaks. Expects that
existing line breaks are posix newlines.
Preserve all white space except added line breaks consume the space on
which they break the line.
Don't wrap long words, thus the output text may have lines longer than
``width``.
... |
A word-wrap function that preserves existing line breaks. Expects that
existing line breaks are posix newlines. | def wrap(text, width):
"""
A word-wrap function that preserves existing line breaks. Expects that
existing line breaks are posix newlines.
Preserve all white space except added line breaks consume the space on
which they break the line.
Don't wrap long words, thus the output text may have line... | [
"def",
"wrap",
"(",
"text",
",",
"width",
")",
":",
"def",
"_generator",
"(",
")",
":",
"for",
"line",
"in",
"text",
".",
"splitlines",
"(",
"True",
")",
":",
"# True keeps trailing linebreaks",
"max_width",
"=",
"min",
"(",
"(",
"line",
".",
"endswith",... | [
27,
0
] | [
54,
32
] | python | en | ['en', 'error', 'th'] | False |
get_valid_filename | (s) |
Return the given string converted to a string that can be used for a clean
filename. Remove leading and trailing spaces; convert other spaces to
underscores; and remove anything that is not an alphanumeric, dash,
underscore, or dot.
>>> get_valid_filename("john's portrait in 2004.jpg")
'johns_p... |
Return the given string converted to a string that can be used for a clean
filename. Remove leading and trailing spaces; convert other spaces to
underscores; and remove anything that is not an alphanumeric, dash,
underscore, or dot.
>>> get_valid_filename("john's portrait in 2004.jpg")
'johns_p... | def get_valid_filename(s):
"""
Return the given string converted to a string that can be used for a clean
filename. Remove leading and trailing spaces; convert other spaces to
underscores; and remove anything that is not an alphanumeric, dash,
underscore, or dot.
>>> get_valid_filename("john's p... | [
"def",
"get_valid_filename",
"(",
"s",
")",
":",
"s",
"=",
"str",
"(",
"s",
")",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
"return",
"re",
".",
"sub",
"(",
"r'(?u)[^-\\w.]'",
",",
"''",
",",
"s",
")"
] | [
220,
0
] | [
230,
40
] | python | en | ['en', 'error', 'th'] | False |
get_text_list | (list_, last_word=gettext_lazy('or')) |
>>> get_text_list(['a', 'b', 'c', 'd'])
'a, b, c or d'
>>> get_text_list(['a', 'b', 'c'], 'and')
'a, b and c'
>>> get_text_list(['a', 'b'], 'and')
'a and b'
>>> get_text_list(['a'])
'a'
>>> get_text_list([])
''
|
>>> get_text_list(['a', 'b', 'c', 'd'])
'a, b, c or d'
>>> get_text_list(['a', 'b', 'c'], 'and')
'a, b and c'
>>> get_text_list(['a', 'b'], 'and')
'a and b'
>>> get_text_list(['a'])
'a'
>>> get_text_list([])
''
| def get_text_list(list_, last_word=gettext_lazy('or')):
"""
>>> get_text_list(['a', 'b', 'c', 'd'])
'a, b, c or d'
>>> get_text_list(['a', 'b', 'c'], 'and')
'a, b and c'
>>> get_text_list(['a', 'b'], 'and')
'a and b'
>>> get_text_list(['a'])
'a'
>>> get_text_list([])
''
"... | [
"def",
"get_text_list",
"(",
"list_",
",",
"last_word",
"=",
"gettext_lazy",
"(",
"'or'",
")",
")",
":",
"if",
"not",
"list_",
":",
"return",
"''",
"if",
"len",
"(",
"list_",
")",
"==",
"1",
":",
"return",
"str",
"(",
"list_",
"[",
"0",
"]",
")",
... | [
234,
0
] | [
254,
5
] | python | en | ['en', 'error', 'th'] | False |
normalize_newlines | (text) | Normalize CRLF and CR newlines to just LF. | Normalize CRLF and CR newlines to just LF. | def normalize_newlines(text):
"""Normalize CRLF and CR newlines to just LF."""
return re_newlines.sub('\n', str(text)) | [
"def",
"normalize_newlines",
"(",
"text",
")",
":",
"return",
"re_newlines",
".",
"sub",
"(",
"'\\n'",
",",
"str",
"(",
"text",
")",
")"
] | [
258,
0
] | [
260,
43
] | python | en | ['en', 'en', 'en'] | True |
phone2numeric | (phone) | Convert a phone number with letters into its numeric equivalent. | Convert a phone number with letters into its numeric equivalent. | def phone2numeric(phone):
"""Convert a phone number with letters into its numeric equivalent."""
char2number = {
'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3', 'g': '4',
'h': '4', 'i': '4', 'j': '5', 'k': '5', 'l': '5', 'm': '6', 'n': '6',
'o': '6', 'p': '7', 'q': '7', 'r': ... | [
"def",
"phone2numeric",
"(",
"phone",
")",
":",
"char2number",
"=",
"{",
"'a'",
":",
"'2'",
",",
"'b'",
":",
"'2'",
",",
"'c'",
":",
"'2'",
",",
"'d'",
":",
"'3'",
",",
"'e'",
":",
"'3'",
",",
"'f'",
":",
"'3'",
",",
"'g'",
":",
"'4'",
",",
"... | [
264,
0
] | [
272,
64
] | python | en | ['en', 'en', 'en'] | True |
smart_split | (text) | r"""
Generator that splits a string by spaces, leaving quoted phrases together.
Supports both single and double quotes, and supports escaping quotes with
backslashes. In the output, strings will keep their initial and trailing
quote marks and escaped quotes will remain escaped (the results can then
... | r"""
Generator that splits a string by spaces, leaving quoted phrases together.
Supports both single and double quotes, and supports escaping quotes with
backslashes. In the output, strings will keep their initial and trailing
quote marks and escaped quotes will remain escaped (the results can then
... | def smart_split(text):
r"""
Generator that splits a string by spaces, leaving quoted phrases together.
Supports both single and double quotes, and supports escaping quotes with
backslashes. In the output, strings will keep their initial and trailing
quote marks and escaped quotes will remain escaped... | [
"def",
"smart_split",
"(",
"text",
")",
":",
"for",
"bit",
"in",
"smart_split_re",
".",
"finditer",
"(",
"str",
"(",
"text",
")",
")",
":",
"yield",
"bit",
".",
"group",
"(",
"0",
")"
] | [
319,
0
] | [
335,
26
] | python | cy | ['en', 'cy', 'hi'] | False |
unescape_string_literal | (s) | r"""
Convert quoted string literals to unquoted strings with escaped quotes and
backslashes unquoted::
>>> unescape_string_literal('"abc"')
'abc'
>>> unescape_string_literal("'abc'")
'abc'
>>> unescape_string_literal('"a \"bc\""')
'a "bc"'
>>> unescape_st... | r"""
Convert quoted string literals to unquoted strings with escaped quotes and
backslashes unquoted:: | def unescape_string_literal(s):
r"""
Convert quoted string literals to unquoted strings with escaped quotes and
backslashes unquoted::
>>> unescape_string_literal('"abc"')
'abc'
>>> unescape_string_literal("'abc'")
'abc'
>>> unescape_string_literal('"a \"bc\""')
... | [
"def",
"unescape_string_literal",
"(",
"s",
")",
":",
"if",
"s",
"[",
"0",
"]",
"not",
"in",
"\"\\\"'\"",
"or",
"s",
"[",
"-",
"1",
"]",
"!=",
"s",
"[",
"0",
"]",
":",
"raise",
"ValueError",
"(",
"\"Not a string literal: %r\"",
"%",
"s",
")",
"quote"... | [
371,
0
] | [
388,
70
] | python | cy | ['en', 'cy', 'hi'] | False |
slugify | (value, allow_unicode=False) |
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.
Remove characters that aren't alphanumerics, underscores, or hyphens.
Convert to lowercase. Also strip leading and trailing whitespace.
|
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.
Remove characters that aren't alphanumerics, underscores, or hyphens.
Convert to lowercase. Also strip leading and trailing whitespace.
| def slugify(value, allow_unicode=False):
"""
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.
Remove characters that aren't alphanumerics, underscores, or hyphens.
Convert to lowercase. Also strip leading and trailing whitespace.
"""
value = str(value)
if allow_unicod... | [
"def",
"slugify",
"(",
"value",
",",
"allow_unicode",
"=",
"False",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"if",
"allow_unicode",
":",
"value",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFKC'",
",",
"value",
")",
"else",
":",
"value",
"="... | [
392,
0
] | [
404,
40
] | python | en | ['en', 'error', 'th'] | False |
camel_case_to_spaces | (value) |
Split CamelCase and convert to lowercase. Strip surrounding whitespace.
|
Split CamelCase and convert to lowercase. Strip surrounding whitespace.
| def camel_case_to_spaces(value):
"""
Split CamelCase and convert to lowercase. Strip surrounding whitespace.
"""
return re_camel_case.sub(r' \1', value).strip().lower() | [
"def",
"camel_case_to_spaces",
"(",
"value",
")",
":",
"return",
"re_camel_case",
".",
"sub",
"(",
"r' \\1'",
",",
"value",
")",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")"
] | [
407,
0
] | [
411,
59
] | python | en | ['en', 'error', 'th'] | False |
_format_lazy | (format_string, *args, **kwargs) |
Apply str.format() on 'format_string' where format_string, args,
and/or kwargs might be lazy.
|
Apply str.format() on 'format_string' where format_string, args,
and/or kwargs might be lazy.
| def _format_lazy(format_string, *args, **kwargs):
"""
Apply str.format() on 'format_string' where format_string, args,
and/or kwargs might be lazy.
"""
return format_string.format(*args, **kwargs) | [
"def",
"_format_lazy",
"(",
"format_string",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"format_string",
".",
"format",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
414,
0
] | [
419,
48
] | python | en | ['en', 'error', 'th'] | False |
Truncator.chars | (self, num, truncate=None, html=False) |
Return the text truncated to be no longer than the specified number
of characters.
`truncate` specifies what should be used to notify that the string has
been truncated, defaulting to a translatable string of an ellipsis.
|
Return the text truncated to be no longer than the specified number
of characters. | def chars(self, num, truncate=None, html=False):
"""
Return the text truncated to be no longer than the specified number
of characters.
`truncate` specifies what should be used to notify that the string has
been truncated, defaulting to a translatable string of an ellipsis.
... | [
"def",
"chars",
"(",
"self",
",",
"num",
",",
"truncate",
"=",
"None",
",",
"html",
"=",
"False",
")",
":",
"self",
".",
"_setup",
"(",
")",
"length",
"=",
"int",
"(",
"num",
")",
"text",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFC'",
",",
"... | [
79,
4
] | [
100,
69
] | python | en | ['en', 'error', 'th'] | False |
Truncator._text_chars | (self, length, truncate, text, truncate_len) | Truncate a string after a certain number of chars. | Truncate a string after a certain number of chars. | def _text_chars(self, length, truncate, text, truncate_len):
"""Truncate a string after a certain number of chars."""
s_len = 0
end_index = None
for i, char in enumerate(text):
if unicodedata.combining(char):
# Don't consider combining characters
... | [
"def",
"_text_chars",
"(",
"self",
",",
"length",
",",
"truncate",
",",
"text",
",",
"truncate_len",
")",
":",
"s_len",
"=",
"0",
"end_index",
"=",
"None",
"for",
"i",
",",
"char",
"in",
"enumerate",
"(",
"text",
")",
":",
"if",
"unicodedata",
".",
"... | [
102,
4
] | [
120,
19
] | python | en | ['en', 'en', 'en'] | True |
Truncator.words | (self, num, truncate=None, html=False) |
Truncate a string after a certain number of words. `truncate` specifies
what should be used to notify that the string has been truncated,
defaulting to ellipsis.
|
Truncate a string after a certain number of words. `truncate` specifies
what should be used to notify that the string has been truncated,
defaulting to ellipsis.
| def words(self, num, truncate=None, html=False):
"""
Truncate a string after a certain number of words. `truncate` specifies
what should be used to notify that the string has been truncated,
defaulting to ellipsis.
"""
self._setup()
length = int(num)
if ht... | [
"def",
"words",
"(",
"self",
",",
"num",
",",
"truncate",
"=",
"None",
",",
"html",
"=",
"False",
")",
":",
"self",
".",
"_setup",
"(",
")",
"length",
"=",
"int",
"(",
"num",
")",
"if",
"html",
":",
"return",
"self",
".",
"_truncate_html",
"(",
"... | [
122,
4
] | [
132,
49
] | python | en | ['en', 'error', 'th'] | False |
Truncator._text_words | (self, length, truncate) |
Truncate a string after a certain number of words.
Strip newlines in the string.
|
Truncate a string after a certain number of words. | def _text_words(self, length, truncate):
"""
Truncate a string after a certain number of words.
Strip newlines in the string.
"""
words = self._wrapped.split()
if len(words) > length:
words = words[:length]
return self.add_truncation_text(' '.join... | [
"def",
"_text_words",
"(",
"self",
",",
"length",
",",
"truncate",
")",
":",
"words",
"=",
"self",
".",
"_wrapped",
".",
"split",
"(",
")",
"if",
"len",
"(",
"words",
")",
">",
"length",
":",
"words",
"=",
"words",
"[",
":",
"length",
"]",
"return"... | [
134,
4
] | [
144,
30
] | python | en | ['en', 'error', 'th'] | False |
Truncator._truncate_html | (self, length, truncate, text, truncate_len, words) |
Truncate HTML to a certain number of chars (not counting tags and
comments), or, if words is True, then to a certain number of words.
Close opened tags if they were correctly closed in the given HTML.
Preserve newlines in the HTML.
|
Truncate HTML to a certain number of chars (not counting tags and
comments), or, if words is True, then to a certain number of words.
Close opened tags if they were correctly closed in the given HTML. | def _truncate_html(self, length, truncate, text, truncate_len, words):
"""
Truncate HTML to a certain number of chars (not counting tags and
comments), or, if words is True, then to a certain number of words.
Close opened tags if they were correctly closed in the given HTML.
Pre... | [
"def",
"_truncate_html",
"(",
"self",
",",
"length",
",",
"truncate",
",",
"text",
",",
"truncate_len",
",",
"words",
")",
":",
"if",
"words",
"and",
"length",
"<=",
"0",
":",
"return",
"''",
"html4_singlets",
"=",
"(",
"'br'",
",",
"'col'",
",",
"'lin... | [
146,
4
] | [
216,
18
] | python | en | ['en', 'error', 'th'] | False |
fast_gradient_method | (
model_fn,
x,
eps,
norm,
clip_min=None,
clip_max=None,
y=None,
targeted=False,
sanity_checks=False,
) |
PyTorch implementation of the Fast Gradient Method.
:param model_fn: a callable that takes an input tensor and returns the model logits.
:param x: input tensor.
:param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572.
:param norm: Order of the norm (mimics NumPy). Possi... |
PyTorch implementation of the Fast Gradient Method.
:param model_fn: a callable that takes an input tensor and returns the model logits.
:param x: input tensor.
:param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572.
:param norm: Order of the norm (mimics NumPy). Possi... | def fast_gradient_method(
model_fn,
x,
eps,
norm,
clip_min=None,
clip_max=None,
y=None,
targeted=False,
sanity_checks=False,
):
"""
PyTorch implementation of the Fast Gradient Method.
:param model_fn: a callable that takes an input tensor and returns the model logits.
... | [
"def",
"fast_gradient_method",
"(",
"model_fn",
",",
"x",
",",
"eps",
",",
"norm",
",",
"clip_min",
"=",
"None",
",",
"clip_max",
"=",
"None",
",",
"y",
"=",
"None",
",",
"targeted",
"=",
"False",
",",
"sanity_checks",
"=",
"False",
",",
")",
":",
"i... | [
7,
0
] | [
102,
16
] | python | en | ['en', 'error', 'th'] | False |
SSM.get_prerequisites | (self) | Gather instance status by calling SSM APIs.
| Gather instance status by calling SSM APIs.
| def get_prerequisites(self):
""" Gather instance status by calling SSM APIs.
"""
if not Cfg.get_int("ssm.enable"):
log.log(log.NOTICE, "SSM support is currently disabled. Set ssm.enable to 1 to enabled it.")
return
now = self.context["now"]
self.ttl ... | [
"def",
"get_prerequisites",
"(",
"self",
")",
":",
"if",
"not",
"Cfg",
".",
"get_int",
"(",
"\"ssm.enable\"",
")",
":",
"log",
".",
"log",
"(",
"log",
".",
"NOTICE",
",",
"\"SSM support is currently disabled. Set ssm.enable to 1 to enabled it.\"",
")",
"return",
"... | [
202,
4
] | [
319,
51
] | python | en | ['en', 'en', 'en'] | True |
SSM.manage_maintenance_windows | (self) | Read SSM Maintenance Window information and apply temporary configuration during maintenance period.
| Read SSM Maintenance Window information and apply temporary configuration during maintenance period.
| def manage_maintenance_windows(self):
""" Read SSM Maintenance Window information and apply temporary configuration during maintenance period.
"""
config_tag = "clonesquad:config:"
def _set_tag(fleet, config, mw):
min_instance_count = None
if "Tags" in mw:
... | [
"def",
"manage_maintenance_windows",
"(",
"self",
")",
":",
"config_tag",
"=",
"\"clonesquad:config:\"",
"def",
"_set_tag",
"(",
"fleet",
",",
"config",
",",
"mw",
")",
":",
"min_instance_count",
"=",
"None",
"if",
"\"Tags\"",
"in",
"mw",
":",
"tags",
"=",
"... | [
674,
4
] | [
759,
100
] | python | en | ['en', 'en', 'en'] | True |
SequenceLikelihood.get_num_categories | (cls) | :returns: The number of likelihood categories in the enum. | :returns: The number of likelihood categories in the enum. | def get_num_categories(cls):
""":returns: The number of likelihood categories in the enum."""
return 4 | [
"def",
"get_num_categories",
"(",
"cls",
")",
":",
"return",
"4"
] | [
59,
4
] | [
61,
16
] | python | en | ['en', 'af', 'en'] | True |
HTTPSitemapTests.test_simple_sitemap_index | (self) | A simple sitemap index can be rendered | A simple sitemap index can be rendered | def test_simple_sitemap_index(self):
"A simple sitemap index can be rendered"
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
# The URL for views.sitemap in tests/urls/http.py has been updated
# with a name but sinc... | [
"def",
"test_simple_sitemap_index",
"(",
"self",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"filterwarnings",
"(",
"\"ignore\"",
",",
"category",
"=",
"RemovedInDjango20Warning",
")",
"# The URL for views.sitemap in tests/urls/h... | [
23,
4
] | [
39,
79
] | python | en | ['en', 'en', 'en'] | True |
HTTPSitemapTests.test_simple_sitemap_custom_index | (self) | A simple sitemap index can be rendered with a custom template | A simple sitemap index can be rendered with a custom template | def test_simple_sitemap_custom_index(self):
"A simple sitemap index can be rendered with a custom template"
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
# The URL for views.sitemap in tests/urls/http.py has been updated
... | [
"def",
"test_simple_sitemap_custom_index",
"(",
"self",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"filterwarnings",
"(",
"\"ignore\"",
",",
"category",
"=",
"RemovedInDjango20Warning",
")",
"# The URL for views.sitemap in tests... | [
44,
4
] | [
61,
79
] | python | en | ['en', 'en', 'en'] | True |
HTTPSitemapTests.test_simple_sitemap_section | (self) | A simple sitemap section can be rendered | A simple sitemap section can be rendered | def test_simple_sitemap_section(self):
"A simple sitemap section can be rendered"
response = self.client.get('/simple/sitemap-simple.xml')
expected_content = """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>%s/location/</loc><lastmo... | [
"def",
"test_simple_sitemap_section",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"'/simple/sitemap-simple.xml'",
")",
"expected_content",
"=",
"\"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/s... | [
63,
4
] | [
71,
79
] | python | en | ['en', 'en', 'en'] | True |
HTTPSitemapTests.test_simple_sitemap | (self) | A simple sitemap can be rendered | A simple sitemap can be rendered | def test_simple_sitemap(self):
"A simple sitemap can be rendered"
response = self.client.get('/simple/sitemap.xml')
expected_content = """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefr... | [
"def",
"test_simple_sitemap",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"'/simple/sitemap.xml'",
")",
"expected_content",
"=",
"\"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n... | [
73,
4
] | [
81,
79
] | python | en | ['en', 'en', 'en'] | True |
HTTPSitemapTests.test_simple_custom_sitemap | (self) | A simple sitemap can be rendered with a custom template | A simple sitemap can be rendered with a custom template | def test_simple_custom_sitemap(self):
"A simple sitemap can be rendered with a custom template"
response = self.client.get('/simple/custom-sitemap.xml')
expected_content = """<?xml version="1.0" encoding="UTF-8"?>
<!-- This is a customised template -->
<urlset xmlns="http://www.sitemaps.org/sche... | [
"def",
"test_simple_custom_sitemap",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"'/simple/custom-sitemap.xml'",
")",
"expected_content",
"=",
"\"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- This is a customised template -->\n<urlset xm... | [
86,
4
] | [
95,
79
] | python | en | ['en', 'en', 'en'] | True |
HTTPSitemapTests.test_sitemap_last_modified | (self) | Tests that Last-Modified header is set correctly | Tests that Last-Modified header is set correctly | def test_sitemap_last_modified(self):
"Tests that Last-Modified header is set correctly"
response = self.client.get('/lastmod/sitemap.xml')
self.assertEqual(response['Last-Modified'], 'Wed, 13 Mar 2013 10:00:00 GMT') | [
"def",
"test_sitemap_last_modified",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"'/lastmod/sitemap.xml'",
")",
"self",
".",
"assertEqual",
"(",
"response",
"[",
"'Last-Modified'",
"]",
",",
"'Wed, 13 Mar 2013 10:00:00 GMT'",
")... | [
97,
4
] | [
100,
84
] | python | en | ['en', 'en', 'en'] | True |
HTTPSitemapTests.test_sitemap_last_modified_date | (self) |
The Last-Modified header should be support dates (without time).
|
The Last-Modified header should be support dates (without time).
| def test_sitemap_last_modified_date(self):
"""
The Last-Modified header should be support dates (without time).
"""
response = self.client.get('/lastmod/date-sitemap.xml')
self.assertEqual(response['Last-Modified'], 'Wed, 13 Mar 2013 00:00:00 GMT') | [
"def",
"test_sitemap_last_modified_date",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"'/lastmod/date-sitemap.xml'",
")",
"self",
".",
"assertEqual",
"(",
"response",
"[",
"'Last-Modified'",
"]",
",",
"'Wed, 13 Mar 2013 00:00:00 G... | [
102,
4
] | [
107,
84
] | python | en | ['en', 'error', 'th'] | False |
HTTPSitemapTests.test_sitemap_last_modified_tz | (self) |
The Last-Modified header should be converted from timezone aware dates
to GMT.
|
The Last-Modified header should be converted from timezone aware dates
to GMT.
| def test_sitemap_last_modified_tz(self):
"""
The Last-Modified header should be converted from timezone aware dates
to GMT.
"""
response = self.client.get('/lastmod/tz-sitemap.xml')
self.assertEqual(response['Last-Modified'], 'Wed, 13 Mar 2013 15:00:00 GMT') | [
"def",
"test_sitemap_last_modified_tz",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"'/lastmod/tz-sitemap.xml'",
")",
"self",
".",
"assertEqual",
"(",
"response",
"[",
"'Last-Modified'",
"]",
",",
"'Wed, 13 Mar 2013 15:00:00 GMT'"... | [
109,
4
] | [
115,
84
] | python | en | ['en', 'error', 'th'] | False |
HTTPSitemapTests.test_sitemap_last_modified_missing | (self) | Tests that Last-Modified header is missing when sitemap has no lastmod | Tests that Last-Modified header is missing when sitemap has no lastmod | def test_sitemap_last_modified_missing(self):
"Tests that Last-Modified header is missing when sitemap has no lastmod"
response = self.client.get('/generic/sitemap.xml')
self.assertFalse(response.has_header('Last-Modified')) | [
"def",
"test_sitemap_last_modified_missing",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"'/generic/sitemap.xml'",
")",
"self",
".",
"assertFalse",
"(",
"response",
".",
"has_header",
"(",
"'Last-Modified'",
")",
")"
] | [
117,
4
] | [
120,
62
] | python | en | ['en', 'en', 'en'] | True |
HTTPSitemapTests.test_sitemap_last_modified_mixed | (self) | Tests that Last-Modified header is omitted when lastmod not on all items | Tests that Last-Modified header is omitted when lastmod not on all items | def test_sitemap_last_modified_mixed(self):
"Tests that Last-Modified header is omitted when lastmod not on all items"
response = self.client.get('/lastmod-mixed/sitemap.xml')
self.assertFalse(response.has_header('Last-Modified')) | [
"def",
"test_sitemap_last_modified_mixed",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"'/lastmod-mixed/sitemap.xml'",
")",
"self",
".",
"assertFalse",
"(",
"response",
".",
"has_header",
"(",
"'Last-Modified'",
")",
")"
] | [
122,
4
] | [
125,
62
] | python | en | ['en', 'en', 'en'] | True |
HTTPSitemapTests.test_localized_priority | (self) | The priority value should not be localized (Refs #14164) | The priority value should not be localized (Refs #14164) | def test_localized_priority(self):
"The priority value should not be localized (Refs #14164)"
activate('fr')
self.assertEqual('0,3', localize(0.3))
# Retrieve the sitemap. Check that priorities
# haven't been rendered in localized format
response = self.client.get('/simp... | [
"def",
"test_localized_priority",
"(",
"self",
")",
":",
"activate",
"(",
"'fr'",
")",
"self",
".",
"assertEqual",
"(",
"'0,3'",
",",
"localize",
"(",
"0.3",
")",
")",
"# Retrieve the sitemap. Check that priorities",
"# haven't been rendered in localized format",
"respo... | [
129,
4
] | [
139,
20
] | python | en | ['en', 'en', 'en'] | True |
HTTPSitemapTests.test_sitemap_get_urls_no_site_1 | (self) |
Check we get ImproperlyConfigured if we don't pass a site object to
Sitemap.get_urls and no Site objects exist
|
Check we get ImproperlyConfigured if we don't pass a site object to
Sitemap.get_urls and no Site objects exist
| def test_sitemap_get_urls_no_site_1(self):
"""
Check we get ImproperlyConfigured if we don't pass a site object to
Sitemap.get_urls and no Site objects exist
"""
Site.objects.all().delete()
self.assertRaises(ImproperlyConfigured, Sitemap().get_urls) | [
"def",
"test_sitemap_get_urls_no_site_1",
"(",
"self",
")",
":",
"Site",
".",
"objects",
".",
"all",
"(",
")",
".",
"delete",
"(",
")",
"self",
".",
"assertRaises",
"(",
"ImproperlyConfigured",
",",
"Sitemap",
"(",
")",
".",
"get_urls",
")"
] | [
155,
4
] | [
161,
67
] | python | en | ['en', 'error', 'th'] | False |
HTTPSitemapTests.test_sitemap_get_urls_no_site_2 | (self) |
Check we get ImproperlyConfigured when we don't pass a site object to
Sitemap.get_urls if Site objects exists, but the sites framework is not
actually installed.
|
Check we get ImproperlyConfigured when we don't pass a site object to
Sitemap.get_urls if Site objects exists, but the sites framework is not
actually installed.
| def test_sitemap_get_urls_no_site_2(self):
"""
Check we get ImproperlyConfigured when we don't pass a site object to
Sitemap.get_urls if Site objects exists, but the sites framework is not
actually installed.
"""
self.assertRaises(ImproperlyConfigured, Sitemap().get_urls) | [
"def",
"test_sitemap_get_urls_no_site_2",
"(",
"self",
")",
":",
"self",
".",
"assertRaises",
"(",
"ImproperlyConfigured",
",",
"Sitemap",
"(",
")",
".",
"get_urls",
")"
] | [
164,
4
] | [
170,
67
] | python | en | ['en', 'error', 'th'] | False |
HTTPSitemapTests.test_sitemap_item | (self) |
Check to make sure that the raw item is included with each
Sitemap.get_url() url result.
|
Check to make sure that the raw item is included with each
Sitemap.get_url() url result.
| def test_sitemap_item(self):
"""
Check to make sure that the raw item is included with each
Sitemap.get_url() url result.
"""
test_sitemap = GenericSitemap({'queryset': TestModel.objects.all()})
def is_testmodel(url):
return isinstance(url['item'], TestModel)... | [
"def",
"test_sitemap_item",
"(",
"self",
")",
":",
"test_sitemap",
"=",
"GenericSitemap",
"(",
"{",
"'queryset'",
":",
"TestModel",
".",
"objects",
".",
"all",
"(",
")",
"}",
")",
"def",
"is_testmodel",
"(",
"url",
")",
":",
"return",
"isinstance",
"(",
... | [
172,
4
] | [
182,
41
] | python | en | ['en', 'error', 'th'] | False |
HTTPSitemapTests.test_cached_sitemap_index | (self) |
Check that a cached sitemap index can be rendered (#2713).
|
Check that a cached sitemap index can be rendered (#2713).
| def test_cached_sitemap_index(self):
"""
Check that a cached sitemap index can be rendered (#2713).
"""
response = self.client.get('/cached/index.xml')
expected_content = """<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
... | [
"def",
"test_cached_sitemap_index",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"'/cached/index.xml'",
")",
"expected_content",
"=",
"\"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitema... | [
184,
4
] | [
194,
79
] | python | en | ['en', 'error', 'th'] | False |
HTTPSitemapTests.test_simple_i18nsitemap_index | (self) | A simple i18n sitemap index can be rendered | A simple i18n sitemap index can be rendered | def test_simple_i18nsitemap_index(self):
"A simple i18n sitemap index can be rendered"
response = self.client.get('/simple/i18n.xml')
expected_content = """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>{0}/en/i18n/testmodel/{1}/</lo... | [
"def",
"test_simple_i18nsitemap_index",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"get",
"(",
"'/simple/i18n.xml'",
")",
"expected_content",
"=",
"\"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0... | [
216,
4
] | [
224,
79
] | python | en | ['en', 'en', 'en'] | True |
MiscTest.test_data_type_schema | (self) |
We really only test this to get test coverage. The
code covered here is really only used in testing tools.
|
We really only test this to get test coverage. The
code covered here is really only used in testing tools.
| def test_data_type_schema(self) -> None:
"""
We really only test this to get test coverage. The
code covered here is really only used in testing tools.
"""
test_schema = DictType(
[
("type", Equals("realm")),
("maybe_n", OptionalType(i... | [
"def",
"test_data_type_schema",
"(",
"self",
")",
"->",
"None",
":",
"test_schema",
"=",
"DictType",
"(",
"[",
"(",
"\"type\"",
",",
"Equals",
"(",
"\"realm\"",
")",
")",
",",
"(",
"\"maybe_n\"",
",",
"OptionalType",
"(",
"int",
")",
")",
",",
"(",
"\"... | [
17,
4
] | [
57,
79
] | python | en | ['en', 'error', 'th'] | False |
get_return_data_type | (func_name) | Return a somewhat-helpful data type given a function name | Return a somewhat-helpful data type given a function name | def get_return_data_type(func_name):
"""Return a somewhat-helpful data type given a function name"""
if func_name.startswith('get_'):
if func_name.endswith('_list'):
return 'List'
elif func_name.endswith('_count'):
return 'Integer'
return '' | [
"def",
"get_return_data_type",
"(",
"func_name",
")",
":",
"if",
"func_name",
".",
"startswith",
"(",
"'get_'",
")",
":",
"if",
"func_name",
".",
"endswith",
"(",
"'_list'",
")",
":",
"return",
"'List'",
"elif",
"func_name",
".",
"endswith",
"(",
"'_count'",... | [
354,
0
] | [
361,
13
] | python | en | ['en', 'en', 'en'] | True |
get_readable_field_data_type | (field) |
Return the description for a given field type, if it exists. Fields'
descriptions can contain format strings, which will be interpolated with
the values of field.__dict__ before being output.
|
Return the description for a given field type, if it exists. Fields'
descriptions can contain format strings, which will be interpolated with
the values of field.__dict__ before being output.
| def get_readable_field_data_type(field):
"""
Return the description for a given field type, if it exists. Fields'
descriptions can contain format strings, which will be interpolated with
the values of field.__dict__ before being output.
"""
return field.description % field.__dict__ | [
"def",
"get_readable_field_data_type",
"(",
"field",
")",
":",
"return",
"field",
".",
"description",
"%",
"field",
".",
"__dict__"
] | [
364,
0
] | [
370,
45
] | python | en | ['en', 'error', 'th'] | False |
extract_views_from_urlpatterns | (urlpatterns, base='', namespace=None) |
Return a list of views from a list of urlpatterns.
Each object in the returned list is a two-tuple: (view_func, regex)
|
Return a list of views from a list of urlpatterns. | def extract_views_from_urlpatterns(urlpatterns, base='', namespace=None):
"""
Return a list of views from a list of urlpatterns.
Each object in the returned list is a two-tuple: (view_func, regex)
"""
views = []
for p in urlpatterns:
if hasattr(p, 'url_patterns'):
try:
... | [
"def",
"extract_views_from_urlpatterns",
"(",
"urlpatterns",
",",
"base",
"=",
"''",
",",
"namespace",
"=",
"None",
")",
":",
"views",
"=",
"[",
"]",
"for",
"p",
"in",
"urlpatterns",
":",
"if",
"hasattr",
"(",
"p",
",",
"'url_patterns'",
")",
":",
"try",... | [
373,
0
] | [
398,
16
] | python | en | ['en', 'error', 'th'] | False |
simplify_regex | (pattern) | r"""
Clean up urlpattern regexes into something more readable by humans. For
example, turn "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$"
into "/<sport_slug>/athletes/<athlete_slug>/".
| r"""
Clean up urlpattern regexes into something more readable by humans. For
example, turn "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$"
into "/<sport_slug>/athletes/<athlete_slug>/".
| def simplify_regex(pattern):
r"""
Clean up urlpattern regexes into something more readable by humans. For
example, turn "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$"
into "/<sport_slug>/athletes/<athlete_slug>/".
"""
pattern = replace_named_groups(pattern)
pattern = replace_unnamed... | [
"def",
"simplify_regex",
"(",
"pattern",
")",
":",
"pattern",
"=",
"replace_named_groups",
"(",
"pattern",
")",
"pattern",
"=",
"replace_unnamed_groups",
"(",
"pattern",
")",
"# clean up any outstanding regex-y characters.",
"pattern",
"=",
"pattern",
".",
"replace",
... | [
401,
0
] | [
413,
18
] | python | cy | ['en', 'cy', 'hi'] | False |
get_addition_model_spec | (do_fail=False) |
Returns the input/output spec for an addition model along with test data.
Can also return test data that causes the test to fail.
:param do_fail Return test data that makes the test fail
|
Returns the input/output spec for an addition model along with test data.
Can also return test data that causes the test to fail. | def get_addition_model_spec(do_fail=False):
"""
Returns the input/output spec for an addition model along with test data.
Can also return test data that causes the test to fail.
:param do_fail Return test data that makes the test fail
"""
return dict(
input_spec=[
{"na... | [
"def",
"get_addition_model_spec",
"(",
"do_fail",
"=",
"False",
")",
":",
"return",
"dict",
"(",
"input_spec",
"=",
"[",
"{",
"\"name\"",
":",
"\"x\"",
",",
"\"dtype\"",
":",
"\"float32\"",
",",
"\"shape\"",
":",
"(",
"\"batch_size\"",
",",
")",
"}",
",",
... | [
19,
0
] | [
40,
5
] | python | en | ['en', 'error', 'th'] | False |
get_string_concat_model_spec | (do_fail=False) |
Returns the input/output spec for a string concatenation model along with
test data. Can also return test data that causes the test to fail.
:param do_fail Return test data that makes the test fail
|
Returns the input/output spec for a string concatenation model along with
test data. Can also return test data that causes the test to fail. | def get_string_concat_model_spec(do_fail=False):
"""
Returns the input/output spec for a string concatenation model along with
test data. Can also return test data that causes the test to fail.
:param do_fail Return test data that makes the test fail
"""
if do_fail:
expected_out = ... | [
"def",
"get_string_concat_model_spec",
"(",
"do_fail",
"=",
"False",
")",
":",
"if",
"do_fail",
":",
"expected_out",
"=",
"np",
".",
"array",
"(",
"[",
"\"a\"",
",",
"\"b\"",
",",
"\"c\"",
"]",
")",
"else",
":",
"expected_out",
"=",
"np",
".",
"array",
... | [
43,
0
] | [
66,
5
] | python | en | ['en', 'error', 'th'] | False |
get_mixed_model_spec | (do_fail=False) |
Returns the input/output spec for a mixed type model along with test data.
Can also return test data that causes the test to fail.
:param do_fail Return test data that makes the test fail
|
Returns the input/output spec for a mixed type model along with test data.
Can also return test data that causes the test to fail. | def get_mixed_model_spec(do_fail=False):
"""
Returns the input/output spec for a mixed type model along with test data.
Can also return test data that causes the test to fail.
:param do_fail Return test data that makes the test fail
"""
return dict(
input_spec=[
{"name... | [
"def",
"get_mixed_model_spec",
"(",
"do_fail",
"=",
"False",
")",
":",
"return",
"dict",
"(",
"input_spec",
"=",
"[",
"{",
"\"name\"",
":",
"\"x\"",
",",
"\"dtype\"",
":",
"\"float32\"",
",",
"\"shape\"",
":",
"(",
"\"batch_size\"",
",",
")",
"}",
",",
"... | [
69,
0
] | [
94,
5
] | python | en | ['en', 'error', 'th'] | False |
check_addition_model | (neuropod_path) |
Validate that the inputs and outputs of the loaded neuropod match
the problem spec
|
Validate that the inputs and outputs of the loaded neuropod match
the problem spec
| def check_addition_model(neuropod_path):
"""
Validate that the inputs and outputs of the loaded neuropod match
the problem spec
"""
with load_neuropod(neuropod_path) as neuropod:
target = get_addition_model_spec()
# Validate that the specs match
check_specs_match(neuropod.in... | [
"def",
"check_addition_model",
"(",
"neuropod_path",
")",
":",
"with",
"load_neuropod",
"(",
"neuropod_path",
")",
"as",
"neuropod",
":",
"target",
"=",
"get_addition_model_spec",
"(",
")",
"# Validate that the specs match",
"check_specs_match",
"(",
"neuropod",
".",
... | [
97,
0
] | [
117,
69
] | python | en | ['en', 'error', 'th'] | False |
check_strings_model | (neuropod_path) |
Validate that the inputs and outputs of the loaded neuropod match
the problem spec
|
Validate that the inputs and outputs of the loaded neuropod match
the problem spec
| def check_strings_model(neuropod_path):
"""
Validate that the inputs and outputs of the loaded neuropod match
the problem spec
"""
with load_neuropod(neuropod_path, _always_use_native=False) as neuropod:
target = get_string_concat_model_spec()
# Validate that the specs match
... | [
"def",
"check_strings_model",
"(",
"neuropod_path",
")",
":",
"with",
"load_neuropod",
"(",
"neuropod_path",
",",
"_always_use_native",
"=",
"False",
")",
"as",
"neuropod",
":",
"target",
"=",
"get_string_concat_model_spec",
"(",
")",
"# Validate that the specs match",
... | [
120,
0
] | [
130,
66
] | python | en | ['en', 'error', 'th'] | False |
check_specs_match | (specs, targets) |
Check that `specs` matches `targets`
:param specs A list of dicts
:param targets A list of dicts
|
Check that `specs` matches `targets` | def check_specs_match(specs, targets):
"""
Check that `specs` matches `targets`
:param specs A list of dicts
:param targets A list of dicts
"""
if len(specs) != len(targets):
raise ValueError("Length of specs and targets do not match!")
for spec, target in zip(specs, ta... | [
"def",
"check_specs_match",
"(",
"specs",
",",
"targets",
")",
":",
"if",
"len",
"(",
"specs",
")",
"!=",
"len",
"(",
"targets",
")",
":",
"raise",
"ValueError",
"(",
"\"Length of specs and targets do not match!\"",
")",
"for",
"spec",
",",
"target",
"in",
"... | [
133,
0
] | [
148,
87
] | python | en | ['en', 'error', 'th'] | False |
add_provision_check_override_param | (parser: ArgumentParser) |
Registers --skip-provision-check argument to be used with various commands/tests in our tools.
|
Registers --skip-provision-check argument to be used with various commands/tests in our tools.
| def add_provision_check_override_param(parser: ArgumentParser) -> None:
"""
Registers --skip-provision-check argument to be used with various commands/tests in our tools.
"""
parser.add_argument(
"--skip-provision-check",
action="store_true",
help="Skip check that provision has b... | [
"def",
"add_provision_check_override_param",
"(",
"parser",
":",
"ArgumentParser",
")",
"->",
"None",
":",
"parser",
".",
"add_argument",
"(",
"\"--skip-provision-check\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Skip check that provision has been run; ... | [
93,
0
] | [
101,
5
] | python | en | ['en', 'error', 'th'] | False |
invalid_config_error_message | (action, key, val) | Returns a better error message when invalid configuration option
is provided. | Returns a better error message when invalid configuration option
is provided. | def invalid_config_error_message(action, key, val):
"""Returns a better error message when invalid configuration option
is provided."""
if action in ('store_true', 'store_false'):
return ("{0} is not a valid value for {1} option, "
"please specify a boolean value like yes/no, "
... | [
"def",
"invalid_config_error_message",
"(",
"action",
",",
"key",
",",
"val",
")",
":",
"if",
"action",
"in",
"(",
"'store_true'",
",",
"'store_false'",
")",
":",
"return",
"(",
"\"{0} is not a valid value for {1} option, \"",
"\"please specify a boolean value like yes/no... | [
255,
0
] | [
265,
40
] | python | en | ['en', 'fr', 'en'] | True |
PrettyHelpFormatter._format_option_strings | (self, option, mvarfmt=' <{}>', optsep=', ') |
Return a comma-separated list of option strings and metavars.
:param option: tuple of (short opt, long opt), e.g: ('-f', '--format')
:param mvarfmt: metavar format string
:param optsep: separator
|
Return a comma-separated list of option strings and metavars. | def _format_option_strings(self, option, mvarfmt=' <{}>', optsep=', '):
"""
Return a comma-separated list of option strings and metavars.
:param option: tuple of (short opt, long opt), e.g: ('-f', '--format')
:param mvarfmt: metavar format string
:param optsep: separator
... | [
"def",
"_format_option_strings",
"(",
"self",
",",
"option",
",",
"mvarfmt",
"=",
"' <{}>'",
",",
"optsep",
"=",
"', '",
")",
":",
"opts",
"=",
"[",
"]",
"if",
"option",
".",
"_short_opts",
":",
"opts",
".",
"append",
"(",
"option",
".",
"_short_opts",
... | [
35,
4
] | [
56,
28
] | python | en | ['en', 'error', 'th'] | False |
PrettyHelpFormatter.format_usage | (self, usage) |
Ensure there is only one newline between usage and the first heading
if there is no description.
|
Ensure there is only one newline between usage and the first heading
if there is no description.
| def format_usage(self, usage):
"""
Ensure there is only one newline between usage and the first heading
if there is no description.
"""
msg = '\nUsage: {}\n'.format(
self.indent_lines(textwrap.dedent(usage), " "))
return msg | [
"def",
"format_usage",
"(",
"self",
",",
"usage",
")",
":",
"msg",
"=",
"'\\nUsage: {}\\n'",
".",
"format",
"(",
"self",
".",
"indent_lines",
"(",
"textwrap",
".",
"dedent",
"(",
"usage",
")",
",",
"\" \"",
")",
")",
"return",
"msg"
] | [
63,
4
] | [
70,
18
] | python | en | ['en', 'error', 'th'] | False |
CustomOptionParser.insert_option_group | (self, idx, *args, **kwargs) | Insert an OptionGroup at a given position. | Insert an OptionGroup at a given position. | def insert_option_group(self, idx, *args, **kwargs):
"""Insert an OptionGroup at a given position."""
group = self.add_option_group(*args, **kwargs)
self.option_groups.pop()
self.option_groups.insert(idx, group)
return group | [
"def",
"insert_option_group",
"(",
"self",
",",
"idx",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"group",
"=",
"self",
".",
"add_option_group",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"option_groups",
".",
"pop",
"(",
... | [
117,
4
] | [
124,
20
] | python | en | ['en', 'en', 'en'] | True |
CustomOptionParser.option_list_all | (self) | Get a list of all options, including those in option groups. | Get a list of all options, including those in option groups. | def option_list_all(self):
"""Get a list of all options, including those in option groups."""
res = self.option_list[:]
for i in self.option_groups:
res.extend(i.option_list)
return res | [
"def",
"option_list_all",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"option_list",
"[",
":",
"]",
"for",
"i",
"in",
"self",
".",
"option_groups",
":",
"res",
".",
"extend",
"(",
"i",
".",
"option_list",
")",
"return",
"res"
] | [
127,
4
] | [
133,
18
] | python | en | ['en', 'en', 'en'] | True |
ConfigOptionParser._update_defaults | (self, defaults) | Updates the given defaults with values from the config files and
the environ. Does a little special handling for certain types of
options (lists). | Updates the given defaults with values from the config files and
the environ. Does a little special handling for certain types of
options (lists). | def _update_defaults(self, defaults):
"""Updates the given defaults with values from the config files and
the environ. Does a little special handling for certain types of
options (lists)."""
# Accumulate complex default state.
self.values = optparse.Values(self.defaults)
... | [
"def",
"_update_defaults",
"(",
"self",
",",
"defaults",
")",
":",
"# Accumulate complex default state.",
"self",
".",
"values",
"=",
"optparse",
".",
"Values",
"(",
"self",
".",
"defaults",
")",
"late_eval",
"=",
"set",
"(",
")",
"# Then set the options with thos... | [
180,
4
] | [
227,
23
] | python | en | ['en', 'en', 'en'] | True |
ConfigOptionParser.get_default_values | (self) | Overriding to make updating the defaults after instantiation of
the option parser possible, _update_defaults() does the dirty work. | Overriding to make updating the defaults after instantiation of
the option parser possible, _update_defaults() does the dirty work. | def get_default_values(self):
"""Overriding to make updating the defaults after instantiation of
the option parser possible, _update_defaults() does the dirty work."""
if not self.process_default_values:
# Old, pre-Optik 1.5 behaviour.
return optparse.Values(self.defaults... | [
"def",
"get_default_values",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"process_default_values",
":",
"# Old, pre-Optik 1.5 behaviour.",
"return",
"optparse",
".",
"Values",
"(",
"self",
".",
"defaults",
")",
"# Load the configuration, or error out in case of an er... | [
229,
4
] | [
248,
40
] | python | en | ['en', 'en', 'en'] | True |
find_commands | (management_dir) |
Given a path to a management directory, returns a list of all the command
names that are available.
Returns an empty list if no commands are defined.
|
Given a path to a management directory, returns a list of all the command
names that are available. | def find_commands(management_dir):
"""
Given a path to a management directory, returns a list of all the command
names that are available.
Returns an empty list if no commands are defined.
"""
command_dir = os.path.join(management_dir, 'commands')
try:
return [f[:-3] for f in os.lis... | [
"def",
"find_commands",
"(",
"management_dir",
")",
":",
"command_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"management_dir",
",",
"'commands'",
")",
"try",
":",
"return",
"[",
"f",
"[",
":",
"-",
"3",
"]",
"for",
"f",
"in",
"os",
".",
"listdir... | [
18,
0
] | [
30,
17
] | python | en | ['en', 'error', 'th'] | False |
load_command_class | (app_name, name) |
Given a command name and an application name, returns the Command
class instance. All errors raised by the import process
(ImportError, AttributeError) are allowed to propagate.
|
Given a command name and an application name, returns the Command
class instance. All errors raised by the import process
(ImportError, AttributeError) are allowed to propagate.
| def load_command_class(app_name, name):
"""
Given a command name and an application name, returns the Command
class instance. All errors raised by the import process
(ImportError, AttributeError) are allowed to propagate.
"""
module = import_module('%s.management.commands.%s' % (app_name, name))... | [
"def",
"load_command_class",
"(",
"app_name",
",",
"name",
")",
":",
"module",
"=",
"import_module",
"(",
"'%s.management.commands.%s'",
"%",
"(",
"app_name",
",",
"name",
")",
")",
"return",
"module",
".",
"Command",
"(",
")"
] | [
33,
0
] | [
40,
27
] | python | en | ['en', 'error', 'th'] | False |
get_commands | () |
Returns a dictionary mapping command names to their callback applications.
This works by looking for a management.commands package in django.core, and
in each installed application -- if a commands package exists, all commands
in that package are registered.
Core commands are always included. If ... |
Returns a dictionary mapping command names to their callback applications. | def get_commands():
"""
Returns a dictionary mapping command names to their callback applications.
This works by looking for a management.commands package in django.core, and
in each installed application -- if a commands package exists, all commands
in that package are registered.
Core comman... | [
"def",
"get_commands",
"(",
")",
":",
"commands",
"=",
"{",
"name",
":",
"'django.core'",
"for",
"name",
"in",
"find_commands",
"(",
"__path__",
"[",
"0",
"]",
")",
"}",
"if",
"not",
"settings",
".",
"configured",
":",
"return",
"commands",
"for",
"app_c... | [
44,
0
] | [
75,
19
] | python | en | ['en', 'error', 'th'] | False |
call_command | (name, *args, **options) |
Calls the given command, with the given options and args/kwargs.
This is the primary API you should use for calling specific commands.
Some examples:
call_command('syncdb')
call_command('shell', plain=True)
call_command('sqlall', 'myapp')
|
Calls the given command, with the given options and args/kwargs. | def call_command(name, *args, **options):
"""
Calls the given command, with the given options and args/kwargs.
This is the primary API you should use for calling specific commands.
Some examples:
call_command('syncdb')
call_command('shell', plain=True)
call_command('sqlall', 'm... | [
"def",
"call_command",
"(",
"name",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"# Load the command object.",
"try",
":",
"app_name",
"=",
"get_commands",
"(",
")",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"CommandError",
"(",
"\"Unk... | [
78,
0
] | [
117,
45
] | python | en | ['en', 'error', 'th'] | False |
execute_from_command_line | (argv=None) |
A simple method that runs a ManagementUtility.
|
A simple method that runs a ManagementUtility.
| def execute_from_command_line(argv=None):
"""
A simple method that runs a ManagementUtility.
"""
utility = ManagementUtility(argv)
utility.execute() | [
"def",
"execute_from_command_line",
"(",
"argv",
"=",
"None",
")",
":",
"utility",
"=",
"ManagementUtility",
"(",
"argv",
")",
"utility",
".",
"execute",
"(",
")"
] | [
330,
0
] | [
335,
21
] | python | en | ['en', 'error', 'th'] | False |
ManagementUtility.main_help_text | (self, commands_only=False) |
Returns the script's main help text, as a string.
|
Returns the script's main help text, as a string.
| def main_help_text(self, commands_only=False):
"""
Returns the script's main help text, as a string.
"""
if commands_only:
usage = sorted(get_commands().keys())
else:
usage = [
"",
"Type '%s help <subcommand>' for help on a ... | [
"def",
"main_help_text",
"(",
"self",
",",
"commands_only",
"=",
"False",
")",
":",
"if",
"commands_only",
":",
"usage",
"=",
"sorted",
"(",
"get_commands",
"(",
")",
".",
"keys",
"(",
")",
")",
"else",
":",
"usage",
"=",
"[",
"\"\"",
",",
"\"Type '%s ... | [
132,
4
] | [
165,
31
] | python | en | ['en', 'error', 'th'] | False |
ManagementUtility.fetch_command | (self, subcommand) |
Tries to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"django-admin" or "manage.py") if it can't be found.
|
Tries to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"django-admin" or "manage.py") if it can't be found.
| def fetch_command(self, subcommand):
"""
Tries to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"django-admin" or "manage.py") if it can't be found.
"""
# Get commands outside of try block to prevent swal... | [
"def",
"fetch_command",
"(",
"self",
",",
"subcommand",
")",
":",
"# Get commands outside of try block to prevent swallowing exceptions",
"commands",
"=",
"get_commands",
"(",
")",
"try",
":",
"app_name",
"=",
"commands",
"[",
"subcommand",
"]",
"except",
"KeyError",
... | [
167,
4
] | [
188,
20
] | python | en | ['en', 'error', 'th'] | False |
ManagementUtility.autocomplete | (self) |
Output completion suggestions for BASH.
The output of this function is passed to BASH's `COMREPLY` variable and
treated as completion suggestions. `COMREPLY` expects a space
separated string as the result.
The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used
... |
Output completion suggestions for BASH. | def autocomplete(self):
"""
Output completion suggestions for BASH.
The output of this function is passed to BASH's `COMREPLY` variable and
treated as completion suggestions. `COMREPLY` expects a space
separated string as the result.
The `COMP_WORDS` and `COMP_CWORD` BA... | [
"def",
"autocomplete",
"(",
"self",
")",
":",
"# Don't complete if user hasn't sourced bash_completion file.",
"if",
"'DJANGO_AUTO_COMPLETE'",
"not",
"in",
"os",
".",
"environ",
":",
"return",
"cwords",
"=",
"os",
".",
"environ",
"[",
"'COMP_WORDS'",
"]",
".",
"spli... | [
190,
4
] | [
268,
19
] | python | en | ['en', 'error', 'th'] | False |
ManagementUtility.execute | (self) |
Given the command-line arguments, this figures out which subcommand is
being run, creates a parser appropriate to that command, and runs it.
|
Given the command-line arguments, this figures out which subcommand is
being run, creates a parser appropriate to that command, and runs it.
| def execute(self):
"""
Given the command-line arguments, this figures out which subcommand is
being run, creates a parser appropriate to that command, and runs it.
"""
try:
subcommand = self.argv[1]
except IndexError:
subcommand = 'help' # Display... | [
"def",
"execute",
"(",
"self",
")",
":",
"try",
":",
"subcommand",
"=",
"self",
".",
"argv",
"[",
"1",
"]",
"except",
"IndexError",
":",
"subcommand",
"=",
"'help'",
"# Display help if no arguments were given.",
"# Preprocess options to extract --settings and --pythonpa... | [
270,
4
] | [
327,
67
] | python | en | ['en', 'error', 'th'] | False |
localtime | (value) |
Converts a datetime to local time in the active time zone.
This only makes sense within a {% localtime off %} block.
|
Converts a datetime to local time in the active time zone. | def localtime(value):
"""
Converts a datetime to local time in the active time zone.
This only makes sense within a {% localtime off %} block.
"""
return do_timezone(value, timezone.get_current_timezone()) | [
"def",
"localtime",
"(",
"value",
")",
":",
"return",
"do_timezone",
"(",
"value",
",",
"timezone",
".",
"get_current_timezone",
"(",
")",
")"
] | [
24,
0
] | [
30,
62
] | python | en | ['en', 'error', 'th'] | False |
utc | (value) |
Converts a datetime to UTC.
|
Converts a datetime to UTC.
| def utc(value):
"""
Converts a datetime to UTC.
"""
return do_timezone(value, timezone.utc) | [
"def",
"utc",
"(",
"value",
")",
":",
"return",
"do_timezone",
"(",
"value",
",",
"timezone",
".",
"utc",
")"
] | [
34,
0
] | [
38,
43
] | python | en | ['en', 'error', 'th'] | False |
do_timezone | (value, arg) |
Converts a datetime to local time in a given time zone.
The argument must be an instance of a tzinfo subclass or a time zone name.
If it is a time zone name, pytz is required.
Naive datetimes are assumed to be in local time in the default time zone.
|
Converts a datetime to local time in a given time zone. | def do_timezone(value, arg):
"""
Converts a datetime to local time in a given time zone.
The argument must be an instance of a tzinfo subclass or a time zone name.
If it is a time zone name, pytz is required.
Naive datetimes are assumed to be in local time in the default time zone.
"""
if ... | [
"def",
"do_timezone",
"(",
"value",
",",
"arg",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"datetime",
")",
":",
"return",
"''",
"# Obtain a timezone-aware datetime",
"try",
":",
"if",
"timezone",
".",
"is_naive",
"(",
"value",
")",
":",
"defa... | [
42,
0
] | [
83,
17
] | python | en | ['en', 'error', 'th'] | False |
localtime_tag | (parser, token) |
Forces or prevents conversion of datetime objects to local time,
regardless of the value of ``settings.USE_TZ``.
Sample usage::
{% localtime off %}{{ value_in_utc }}{% endlocaltime %}
|
Forces or prevents conversion of datetime objects to local time,
regardless of the value of ``settings.USE_TZ``. | def localtime_tag(parser, token):
"""
Forces or prevents conversion of datetime objects to local time,
regardless of the value of ``settings.USE_TZ``.
Sample usage::
{% localtime off %}{{ value_in_utc }}{% endlocaltime %}
"""
bits = token.split_contents()
if len(bits) == 1:
... | [
"def",
"localtime_tag",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"==",
"1",
":",
"use_tz",
"=",
"True",
"elif",
"len",
"(",
"bits",
")",
">",
"2",
"or",
"bits",
"... | [
131,
0
] | [
151,
42
] | python | en | ['en', 'error', 'th'] | False |
timezone_tag | (parser, token) |
Enables a given time zone just for this block.
The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
time zone name, or ``None``. If is it a time zone name, pytz is required.
If it is ``None``, the default time zone is used within the block.
Sample usage::
{% timezone... |
Enables a given time zone just for this block. | def timezone_tag(parser, token):
"""
Enables a given time zone just for this block.
The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
time zone name, or ``None``. If is it a time zone name, pytz is required.
If it is ``None``, the default time zone is used within the block.
... | [
"def",
"timezone_tag",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"!=",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'%s' takes one argument (timezone)\"",
"%",
"bits",
"[... | [
155,
0
] | [
177,
37
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.