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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
save | (criteria, report, report_path, adv_x_val) |
Saves the report and adversarial examples.
:param criteria: dict, of the form returned by AttackGoal.get_criteria
:param report: dict containing a confidence report
:param report_path: string, filepath
:param adv_x_val: numpy array containing dataset of adversarial examples
|
Saves the report and adversarial examples.
:param criteria: dict, of the form returned by AttackGoal.get_criteria
:param report: dict containing a confidence report
:param report_path: string, filepath
:param adv_x_val: numpy array containing dataset of adversarial examples
| def save(criteria, report, report_path, adv_x_val):
"""
Saves the report and adversarial examples.
:param criteria: dict, of the form returned by AttackGoal.get_criteria
:param report: dict containing a confidence report
:param report_path: string, filepath
:param adv_x_val: numpy array containi... | [
"def",
"save",
"(",
"criteria",
",",
"report",
",",
"report_path",
",",
"adv_x_val",
")",
":",
"print_stats",
"(",
"criteria",
"[",
"\"correctness\"",
"]",
",",
"criteria",
"[",
"\"confidence\"",
"]",
",",
"\"bundled\"",
")",
"print",
"(",
"\"Saving to \"",
... | [
605,
0
] | [
620,
34
] | python | en | ['en', 'error', 'th'] | False |
unfinished_attack_configs | (new_work_goal, work_before, run_counts, log=False) |
Returns a list of attack configs that have not yet been run the desired
number of times.
:param new_work_goal: dict mapping attacks to desired number of times to run
:param work_before: dict mapping attacks to number of times they were run
before starting this new goal. Should be prefiltered to i... |
Returns a list of attack configs that have not yet been run the desired
number of times.
:param new_work_goal: dict mapping attacks to desired number of times to run
:param work_before: dict mapping attacks to number of times they were run
before starting this new goal. Should be prefiltered to i... | def unfinished_attack_configs(new_work_goal, work_before, run_counts, log=False):
"""
Returns a list of attack configs that have not yet been run the desired
number of times.
:param new_work_goal: dict mapping attacks to desired number of times to run
:param work_before: dict mapping attacks to numb... | [
"def",
"unfinished_attack_configs",
"(",
"new_work_goal",
",",
"work_before",
",",
"run_counts",
",",
"log",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"work_before",
",",
"dict",
")",
",",
"work_before",
"for",
"key",
"in",
"work_before",
":",
"valu... | [
1052,
0
] | [
1097,
25
] | python | en | ['en', 'error', 'th'] | False |
bundle_examples_with_goal | (
sess, model, adv_x_list, y, goal, report_path, batch_size=BATCH_SIZE
) |
A post-processor version of attack bundling, that chooses the strongest
example from the output of multiple earlier bundling strategies.
:param sess: tf.session.Session
:param model: cleverhans.model.Model
:param adv_x_list: list of numpy arrays
Each entry in the list is the output of a prev... |
A post-processor version of attack bundling, that chooses the strongest
example from the output of multiple earlier bundling strategies. | def bundle_examples_with_goal(
sess, model, adv_x_list, y, goal, report_path, batch_size=BATCH_SIZE
):
"""
A post-processor version of attack bundling, that chooses the strongest
example from the output of multiple earlier bundling strategies.
:param sess: tf.session.Session
:param model: cleve... | [
"def",
"bundle_examples_with_goal",
"(",
"sess",
",",
"model",
",",
"adv_x_list",
",",
"y",
",",
"goal",
",",
"report_path",
",",
"batch_size",
"=",
"BATCH_SIZE",
")",
":",
"# Check the input",
"num_attacks",
"=",
"len",
"(",
"adv_x_list",
")",
"assert",
"num_... | [
1177,
0
] | [
1248,
28
] | python | en | ['en', 'error', 'th'] | False |
spsa_max_confidence_recipe | (
sess,
model,
x,
y,
nb_classes,
eps,
clip_min,
clip_max,
nb_iter,
report_path,
spsa_samples=SPSA.DEFAULT_SPSA_SAMPLES,
spsa_iters=SPSA.DEFAULT_SPSA_ITERS,
eval_batch_size=BATCH_SIZE,
) | Runs the MaxConfidence attack using SPSA as the underlying optimizer.
Even though this runs only one attack, it must be implemented as a bundler
because SPSA supports only batch_size=1. The cleverhans.attacks.MaxConfidence
attack internally multiplies the batch size by nb_classes, so it can't take
SPSA... | Runs the MaxConfidence attack using SPSA as the underlying optimizer. | def spsa_max_confidence_recipe(
sess,
model,
x,
y,
nb_classes,
eps,
clip_min,
clip_max,
nb_iter,
report_path,
spsa_samples=SPSA.DEFAULT_SPSA_SAMPLES,
spsa_iters=SPSA.DEFAULT_SPSA_ITERS,
eval_batch_size=BATCH_SIZE,
):
"""Runs the MaxConfidence attack using SPSA as ... | [
"def",
"spsa_max_confidence_recipe",
"(",
"sess",
",",
"model",
",",
"x",
",",
"y",
",",
"nb_classes",
",",
"eps",
",",
"clip_min",
",",
"clip_max",
",",
"nb_iter",
",",
"report_path",
",",
"spsa_samples",
"=",
"SPSA",
".",
"DEFAULT_SPSA_SAMPLES",
",",
"spsa... | [
1251,
0
] | [
1318,
5
] | python | en | ['en', 'en', 'en'] | True |
AttackGoal.start | (self, run_counts) |
Called by the bundler when it starts working on the goal.
:param run_counts: dict mapping AttackConfigs to numpy arrays reporting
how many times they have been run on each example.
|
Called by the bundler when it starts working on the goal. | def start(self, run_counts):
"""
Called by the bundler when it starts working on the goal.
:param run_counts: dict mapping AttackConfigs to numpy arrays reporting
how many times they have been run on each example.
""" | [
"def",
"start",
"(",
"self",
",",
"run_counts",
")",
":"
] | [
639,
4
] | [
645,
11
] | python | en | ['en', 'error', 'th'] | False |
AttackGoal.get_criteria | (self, sess, model, advx, y, batch_size=BATCH_SIZE) |
Returns a dictionary mapping the name of each criterion to a NumPy
array containing the value of that criterion for each adversarial
example.
Subclasses can add extra criteria by implementing the `extra_criteria`
method.
:param sess: tf.session.Session
:param mo... |
Returns a dictionary mapping the name of each criterion to a NumPy
array containing the value of that criterion for each adversarial
example.
Subclasses can add extra criteria by implementing the `extra_criteria`
method. | def get_criteria(self, sess, model, advx, y, batch_size=BATCH_SIZE):
"""
Returns a dictionary mapping the name of each criterion to a NumPy
array containing the value of that criterion for each adversarial
example.
Subclasses can add extra criteria by implementing the `extra_crit... | [
"def",
"get_criteria",
"(",
"self",
",",
"sess",
",",
"model",
",",
"advx",
",",
"y",
",",
"batch_size",
"=",
"BATCH_SIZE",
")",
":",
"names",
",",
"factory",
"=",
"self",
".",
"extra_criteria",
"(",
")",
"factory",
"=",
"_CriteriaFactory",
"(",
"model",... | [
647,
4
] | [
670,
18
] | python | en | ['en', 'error', 'th'] | False |
AttackGoal.extra_criteria | (self) |
Subclasses implement this to specify any extra criteria they need to track.
: returns: list of criterion names, _ExtraCriteriaFactory implementing them
|
Subclasses implement this to specify any extra criteria they need to track.
: returns: list of criterion names, _ExtraCriteriaFactory implementing them
| def extra_criteria(self):
"""
Subclasses implement this to specify any extra criteria they need to track.
: returns: list of criterion names, _ExtraCriteriaFactory implementing them
"""
return [], None | [
"def",
"extra_criteria",
"(",
"self",
")",
":",
"return",
"[",
"]",
",",
"None"
] | [
672,
4
] | [
677,
23
] | python | en | ['en', 'error', 'th'] | False |
AttackGoal.request_examples | (self, attack_config, criteria, run_counts, batch_size) |
Returns a numpy array of integer example indices to run in the next batch.
|
Returns a numpy array of integer example indices to run in the next batch.
| def request_examples(self, attack_config, criteria, run_counts, batch_size):
"""
Returns a numpy array of integer example indices to run in the next batch.
"""
raise NotImplementedError(
str(type(self)) + "needs to implement request_examples"
) | [
"def",
"request_examples",
"(",
"self",
",",
"attack_config",
",",
"criteria",
",",
"run_counts",
",",
"batch_size",
")",
":",
"raise",
"NotImplementedError",
"(",
"str",
"(",
"type",
"(",
"self",
")",
")",
"+",
"\"needs to implement request_examples\"",
")"
] | [
679,
4
] | [
685,
9
] | python | en | ['en', 'error', 'th'] | False |
AttackGoal.is_satisfied | (self, criteria, run_counts) |
Returns a bool indicating whether the goal has been satisfied.
|
Returns a bool indicating whether the goal has been satisfied.
| def is_satisfied(self, criteria, run_counts):
"""
Returns a bool indicating whether the goal has been satisfied.
"""
raise NotImplementedError(str(type(self)) + " needs to implement is_satisfied.") | [
"def",
"is_satisfied",
"(",
"self",
",",
"criteria",
",",
"run_counts",
")",
":",
"raise",
"NotImplementedError",
"(",
"str",
"(",
"type",
"(",
"self",
")",
")",
"+",
"\" needs to implement is_satisfied.\"",
")"
] | [
687,
4
] | [
691,
88
] | python | en | ['en', 'error', 'th'] | False |
AttackGoal.print_progress | (self, criteria, run_counts) |
Prints a progress message about how much has been done toward the goal.
:param criteria: dict, of the format returned by get_criteria
:param run_counts: dict mapping each AttackConfig to a numpy array
specifying how many times it has been run for each example
|
Prints a progress message about how much has been done toward the goal.
:param criteria: dict, of the format returned by get_criteria
:param run_counts: dict mapping each AttackConfig to a numpy array
specifying how many times it has been run for each example
| def print_progress(self, criteria, run_counts):
"""
Prints a progress message about how much has been done toward the goal.
:param criteria: dict, of the format returned by get_criteria
:param run_counts: dict mapping each AttackConfig to a numpy array
specifying how many times... | [
"def",
"print_progress",
"(",
"self",
",",
"criteria",
",",
"run_counts",
")",
":",
"print",
"(",
"\"Working on a \"",
"+",
"self",
".",
"__class__",
".",
"__name__",
"+",
"\" goal.\"",
")"
] | [
693,
4
] | [
700,
67
] | python | en | ['en', 'error', 'th'] | False |
AttackGoal.get_attack_config | (self, attack_configs, run_counts, criteria) |
Returns an AttackConfig to run on the next batch.
|
Returns an AttackConfig to run on the next batch.
| def get_attack_config(self, attack_configs, run_counts, criteria):
"""
Returns an AttackConfig to run on the next batch.
"""
raise NotImplementedError(
str(type(self)) + " needs to implement get_attack_config"
) | [
"def",
"get_attack_config",
"(",
"self",
",",
"attack_configs",
",",
"run_counts",
",",
"criteria",
")",
":",
"raise",
"NotImplementedError",
"(",
"str",
"(",
"type",
"(",
"self",
")",
")",
"+",
"\" needs to implement get_attack_config\"",
")"
] | [
702,
4
] | [
708,
9
] | python | en | ['en', 'error', 'th'] | False |
AttackGoal.new_wins | (self, orig_criteria, orig_idx, new_criteria, new_idx) |
Returns a bool indicating whether a new adversarial example is better
than the pre-existing one for the same clean example.
:param orig_criteria: dict mapping names of criteria to their value
for each example in the whole dataset
:param orig_idx: The position of the pre-existi... |
Returns a bool indicating whether a new adversarial example is better
than the pre-existing one for the same clean example.
:param orig_criteria: dict mapping names of criteria to their value
for each example in the whole dataset
:param orig_idx: The position of the pre-existi... | def new_wins(self, orig_criteria, orig_idx, new_criteria, new_idx):
"""
Returns a bool indicating whether a new adversarial example is better
than the pre-existing one for the same clean example.
:param orig_criteria: dict mapping names of criteria to their value
for each examp... | [
"def",
"new_wins",
"(",
"self",
",",
"orig_criteria",
",",
"orig_idx",
",",
"new_criteria",
",",
"new_idx",
")",
":",
"raise",
"NotImplementedError",
"(",
"str",
"(",
"type",
"(",
"self",
")",
")",
"+",
"\" needs to implement new_wins.\"",
")"
] | [
710,
4
] | [
723,
84
] | python | en | ['en', 'error', 'th'] | False |
Misclassify.filter | (self, run_counts, criteria) |
Return run counts only for examples that are still correctly classified
|
Return run counts only for examples that are still correctly classified
| def filter(self, run_counts, criteria):
"""
Return run counts only for examples that are still correctly classified
"""
correctness = criteria["correctness"]
assert correctness.dtype == np.bool
filtered_counts = deep_copy(run_counts)
for key in filtered_counts:
... | [
"def",
"filter",
"(",
"self",
",",
"run_counts",
",",
"criteria",
")",
":",
"correctness",
"=",
"criteria",
"[",
"\"correctness\"",
"]",
"assert",
"correctness",
".",
"dtype",
"==",
"np",
".",
"bool",
"filtered_counts",
"=",
"deep_copy",
"(",
"run_counts",
"... | [
814,
4
] | [
823,
30
] | python | en | ['en', 'error', 'th'] | False |
MaxConfidence.filter | (self, run_counts, criteria) |
Return the counts for only those examples that are below the threshold
|
Return the counts for only those examples that are below the threshold
| def filter(self, run_counts, criteria):
"""
Return the counts for only those examples that are below the threshold
"""
wrong_confidence = criteria["wrong_confidence"]
below_t = wrong_confidence <= self.t
filtered_counts = deep_copy(run_counts)
for key in filtered_... | [
"def",
"filter",
"(",
"self",
",",
"run_counts",
",",
"criteria",
")",
":",
"wrong_confidence",
"=",
"criteria",
"[",
"\"wrong_confidence\"",
"]",
"below_t",
"=",
"wrong_confidence",
"<=",
"self",
".",
"t",
"filtered_counts",
"=",
"deep_copy",
"(",
"run_counts",... | [
924,
4
] | [
933,
30
] | python | en | ['en', 'error', 'th'] | False |
prepopulated_fields_js | (context) |
Creates a list of prepopulated_fields that should render Javascript for
the prepopulated fields for both the admin form and inlines.
|
Creates a list of prepopulated_fields that should render Javascript for
the prepopulated fields for both the admin form and inlines.
| def prepopulated_fields_js(context):
"""
Creates a list of prepopulated_fields that should render Javascript for
the prepopulated fields for both the admin form and inlines.
"""
prepopulated_fields = []
if 'adminform' in context:
prepopulated_fields.extend(context['adminform'].prepopulat... | [
"def",
"prepopulated_fields_js",
"(",
"context",
")",
":",
"prepopulated_fields",
"=",
"[",
"]",
"if",
"'adminform'",
"in",
"context",
":",
"prepopulated_fields",
".",
"extend",
"(",
"context",
"[",
"'adminform'",
"]",
".",
"prepopulated_fields",
")",
"if",
"'in... | [
6,
0
] | [
20,
18
] | python | en | ['en', 'error', 'th'] | False |
submit_row | (context) |
Displays the row of buttons for delete and save.
|
Displays the row of buttons for delete and save.
| def submit_row(context):
"""
Displays the row of buttons for delete and save.
"""
opts = context['opts']
change = context['change']
is_popup = context['is_popup']
save_as = context['save_as']
ctx = {
'opts': opts,
'show_delete_link': (
not is_popup and context... | [
"def",
"submit_row",
"(",
"context",
")",
":",
"opts",
"=",
"context",
"[",
"'opts'",
"]",
"change",
"=",
"context",
"[",
"'change'",
"]",
"is_popup",
"=",
"context",
"[",
"'is_popup'",
"]",
"save_as",
"=",
"context",
"[",
"'save_as'",
"]",
"ctx",
"=",
... | [
24,
0
] | [
50,
14
] | python | en | ['en', 'error', 'th'] | False |
cell_count | (inline_admin_form) | Returns the number of cells used in a tabular inline | Returns the number of cells used in a tabular inline | def cell_count(inline_admin_form):
"""Returns the number of cells used in a tabular inline"""
count = 1 # Hidden cell with hidden 'id' field
for fieldset in inline_admin_form:
# Loop through all the fields (one per cell)
for line in fieldset:
for field in line:
c... | [
"def",
"cell_count",
"(",
"inline_admin_form",
")",
":",
"count",
"=",
"1",
"# Hidden cell with hidden 'id' field",
"for",
"fieldset",
"in",
"inline_admin_form",
":",
"# Loop through all the fields (one per cell)",
"for",
"line",
"in",
"fieldset",
":",
"for",
"field",
"... | [
54,
0
] | [
65,
16
] | python | en | ['en', 'en', 'en'] | True |
get_root | () | Get the project root directory.
We require that all commands are run from the project root, i.e. the
directory that contains setup.py, setup.cfg, and versioneer.py .
| Get the project root directory. | def get_root():
"""Get the project root directory.
We require that all commands are run from the project root, i.e. the
directory that contains setup.py, setup.cfg, and versioneer.py .
"""
root = os.path.realpath(os.path.abspath(os.getcwd()))
setup_py = os.path.join(root, "setup.py")
versio... | [
"def",
"get_root",
"(",
")",
":",
"root",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
")",
"setup_py",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"\"setup... | [
295,
0
] | [
331,
15
] | python | en | ['en', 'en', 'en'] | True |
get_config_from_root | (root) | Read the project setup.cfg file to determine Versioneer config. | Read the project setup.cfg file to determine Versioneer config. | def get_config_from_root(root):
"""Read the project setup.cfg file to determine Versioneer config."""
# This might raise EnvironmentError (if setup.cfg is missing), or
# configparser.NoSectionError (if it lacks a [versioneer] section), or
# configparser.NoOptionError (if it lacks "VCS="). See the docstr... | [
"def",
"get_config_from_root",
"(",
"root",
")",
":",
"# This might raise EnvironmentError (if setup.cfg is missing), or",
"# configparser.NoSectionError (if it lacks a [versioneer] section), or",
"# configparser.NoOptionError (if it lacks \"VCS=\"). See the docstring at",
"# the top of versioneer... | [
334,
0
] | [
360,
14
] | python | en | ['en', 'en', 'en'] | True |
register_vcs_handler | (vcs, method) | Decorator to mark a method as the handler for a particular VCS. | Decorator to mark a method as the handler for a particular VCS. | def register_vcs_handler(vcs, method): # decorator
"""Decorator to mark a method as the handler for a particular VCS."""
def decorate(f):
"""Store f in HANDLERS[vcs][method]."""
if vcs not in HANDLERS:
HANDLERS[vcs] = {}
HANDLERS[vcs][method] = f
return f
return ... | [
"def",
"register_vcs_handler",
"(",
"vcs",
",",
"method",
")",
":",
"# decorator",
"def",
"decorate",
"(",
"f",
")",
":",
"\"\"\"Store f in HANDLERS[vcs][method].\"\"\"",
"if",
"vcs",
"not",
"in",
"HANDLERS",
":",
"HANDLERS",
"[",
"vcs",
"]",
"=",
"{",
"}",
... | [
372,
0
] | [
380,
19
] | python | en | ['en', 'en', 'en'] | True |
run_command | (commands, args, cwd=None, verbose=False, hide_stderr=False,
env=None) | Call the given command(s). | Call the given command(s). | def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
env=None):
"""Call the given command(s)."""
assert isinstance(commands, list)
p = None
for c in commands:
try:
dispcmd = str([c] + args)
# remember shell=False, so use git.cmd on w... | [
"def",
"run_command",
"(",
"commands",
",",
"args",
",",
"cwd",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"hide_stderr",
"=",
"False",
",",
"env",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"commands",
",",
"list",
")",
"p",
"=",
"None... | [
383,
0
] | [
417,
31
] | python | en | ['en', 'en', 'en'] | True |
git_get_keywords | (versionfile_abs) | Extract version information from the given file. | Extract version information from the given file. | def git_get_keywords(versionfile_abs):
"""Extract version information from the given file."""
# the code embedded in _version.py can just fetch the value of these
# keywords. When used from setup.py, we don't want to import _version.py,
# so we do it with a regexp instead. This function is not used from... | [
"def",
"git_get_keywords",
"(",
"versionfile_abs",
")",
":",
"# the code embedded in _version.py can just fetch the value of these",
"# keywords. When used from setup.py, we don't want to import _version.py,",
"# so we do it with a regexp instead. This function is not used from",
"# _version.py.",... | [
944,
0
] | [
969,
19
] | python | en | ['en', 'en', 'en'] | True |
git_versions_from_keywords | (keywords, tag_prefix, verbose) | Get version information from git keywords. | Get version information from git keywords. | def git_versions_from_keywords(keywords, tag_prefix, verbose):
"""Get version information from git keywords."""
if not keywords:
raise NotThisMethod("no keywords at all, weird")
date = keywords.get("date")
if date is not None:
# git-2.2.0 added "%cI", which expands to an ISO-8601 -compli... | [
"def",
"git_versions_from_keywords",
"(",
"keywords",
",",
"tag_prefix",
",",
"verbose",
")",
":",
"if",
"not",
"keywords",
":",
"raise",
"NotThisMethod",
"(",
"\"no keywords at all, weird\"",
")",
"date",
"=",
"keywords",
".",
"get",
"(",
"\"date\"",
")",
"if",... | [
973,
0
] | [
1024,
70
] | python | en | ['en', 'da', 'en'] | True |
git_pieces_from_vcs | (tag_prefix, root, verbose, run_command=run_command) | Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meaning we're inside a checked out source tree.
| Get version from 'git describe' in the root of the source tree. | def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
"""Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meani... | [
"def",
"git_pieces_from_vcs",
"(",
"tag_prefix",
",",
"root",
",",
"verbose",
",",
"run_command",
"=",
"run_command",
")",
":",
"GITS",
"=",
"[",
"\"git\"",
"]",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"GITS",
"=",
"[",
"\"git.cmd\"",
",",
... | [
1028,
0
] | [
1116,
17
] | python | en | ['en', 'en', 'en'] | True |
do_vcs_install | (manifest_in, versionfile_source, ipy) | Git-specific installation logic for Versioneer.
For Git, this means creating/changing .gitattributes to mark _version.py
for export-subst keyword substitution.
| Git-specific installation logic for Versioneer. | def do_vcs_install(manifest_in, versionfile_source, ipy):
"""Git-specific installation logic for Versioneer.
For Git, this means creating/changing .gitattributes to mark _version.py
for export-subst keyword substitution.
"""
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", ... | [
"def",
"do_vcs_install",
"(",
"manifest_in",
",",
"versionfile_source",
",",
"ipy",
")",
":",
"GITS",
"=",
"[",
"\"git\"",
"]",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
":",
"GITS",
"=",
"[",
"\"git.cmd\"",
",",
"\"git.exe\"",
"]",
"files",
"=",
... | [
1119,
0
] | [
1154,
44
] | python | en | ['en', 'en', 'en'] | True |
versions_from_parentdir | (parentdir_prefix, root, verbose) | Try to determine the version from the parent directory name.
Source tarballs conventionally unpack into a directory that includes both
the project name and a version string. We will also support searching up
two directory levels for an appropriately named parent directory
| Try to determine the version from the parent directory name. | def versions_from_parentdir(parentdir_prefix, root, verbose):
"""Try to determine the version from the parent directory name.
Source tarballs conventionally unpack into a directory that includes both
the project name and a version string. We will also support searching up
two directory levels for an ap... | [
"def",
"versions_from_parentdir",
"(",
"parentdir_prefix",
",",
"root",
",",
"verbose",
")",
":",
"rootdirs",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"root",
")",
"if",
"d... | [
1157,
0
] | [
1179,
70
] | python | en | ['en', 'en', 'en'] | True |
versions_from_file | (filename) | Try to determine the version from _version.py if present. | Try to determine the version from _version.py if present. | def versions_from_file(filename):
"""Try to determine the version from _version.py if present."""
try:
with open(filename) as f:
contents = f.read()
except EnvironmentError:
raise NotThisMethod("unable to read _version.py")
mo = re.search(r"version_json = '''\n(.*)''' # END ... | [
"def",
"versions_from_file",
"(",
"filename",
")",
":",
"try",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"contents",
"=",
"f",
".",
"read",
"(",
")",
"except",
"EnvironmentError",
":",
"raise",
"NotThisMethod",
"(",
"\"unable to read _versio... | [
1200,
0
] | [
1214,
34
] | python | en | ['en', 'en', 'en'] | True |
write_to_version_file | (filename, versions) | Write the given version number to the given _version.py file. | Write the given version number to the given _version.py file. | def write_to_version_file(filename, versions):
"""Write the given version number to the given _version.py file."""
os.unlink(filename)
contents = json.dumps(versions, sort_keys=True,
indent=1, separators=(",", ": "))
with open(filename, "w") as f:
f.write(SHORT_VERSION_... | [
"def",
"write_to_version_file",
"(",
"filename",
",",
"versions",
")",
":",
"os",
".",
"unlink",
"(",
"filename",
")",
"contents",
"=",
"json",
".",
"dumps",
"(",
"versions",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"1",
",",
"separators",
"=",... | [
1217,
0
] | [
1225,
61
] | python | en | ['en', 'en', 'en'] | True |
plus_or_dot | (pieces) | Return a + if we don't already have one, else return a . | Return a + if we don't already have one, else return a . | def plus_or_dot(pieces):
"""Return a + if we don't already have one, else return a ."""
if "+" in pieces.get("closest-tag", ""):
return "."
return "+" | [
"def",
"plus_or_dot",
"(",
"pieces",
")",
":",
"if",
"\"+\"",
"in",
"pieces",
".",
"get",
"(",
"\"closest-tag\"",
",",
"\"\"",
")",
":",
"return",
"\".\"",
"return",
"\"+\""
] | [
1228,
0
] | [
1232,
14
] | python | en | ['en', 'en', 'en'] | True |
render_pep440 | (pieces) | Build up version string, with post-release "local version identifier".
Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
Exceptions:
1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
| Build up version string, with post-release "local version identifier". | def render_pep440(pieces):
"""Build up version string, with post-release "local version identifier".
Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
Exceptions:
1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHE... | [
"def",
"render_pep440",
"(",
"pieces",
")",
":",
"if",
"pieces",
"[",
"\"closest-tag\"",
"]",
":",
"rendered",
"=",
"pieces",
"[",
"\"closest-tag\"",
"]",
"if",
"pieces",
"[",
"\"distance\"",
"]",
"or",
"pieces",
"[",
"\"dirty\"",
"]",
":",
"rendered",
"+=... | [
1235,
0
] | [
1257,
19
] | python | en | ['en', 'en', 'en'] | True |
render_pep440_pre | (pieces) | TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE
| TAG[.post.devDISTANCE] -- No -dirty. | def render_pep440_pre(pieces):
"""TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered += ".post.dev%d" % pieces["distance"]
else:
# exce... | [
"def",
"render_pep440_pre",
"(",
"pieces",
")",
":",
"if",
"pieces",
"[",
"\"closest-tag\"",
"]",
":",
"rendered",
"=",
"pieces",
"[",
"\"closest-tag\"",
"]",
"if",
"pieces",
"[",
"\"distance\"",
"]",
":",
"rendered",
"+=",
"\".post.dev%d\"",
"%",
"pieces",
... | [
1260,
0
] | [
1273,
19
] | python | en | ['en', 'en', 'pt'] | True |
render_pep440_post | (pieces) | TAG[.postDISTANCE[.dev0]+gHEX] .
The ".dev0" means dirty. Note that .dev0 sorts backwards
(a dirty tree will appear "older" than the corresponding clean one),
but you shouldn't be releasing software with -dirty anyways.
Exceptions:
1: no tags. 0.postDISTANCE[.dev0]
| TAG[.postDISTANCE[.dev0]+gHEX] . | def render_pep440_post(pieces):
"""TAG[.postDISTANCE[.dev0]+gHEX] .
The ".dev0" means dirty. Note that .dev0 sorts backwards
(a dirty tree will appear "older" than the corresponding clean one),
but you shouldn't be releasing software with -dirty anyways.
Exceptions:
1: no tags. 0.postDISTANCE[... | [
"def",
"render_pep440_post",
"(",
"pieces",
")",
":",
"if",
"pieces",
"[",
"\"closest-tag\"",
"]",
":",
"rendered",
"=",
"pieces",
"[",
"\"closest-tag\"",
"]",
"if",
"pieces",
"[",
"\"distance\"",
"]",
"or",
"pieces",
"[",
"\"dirty\"",
"]",
":",
"rendered",
... | [
1276,
0
] | [
1300,
19
] | python | cy | ['en', 'cy', 'hi'] | False |
render_pep440_old | (pieces) | TAG[.postDISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.postDISTANCE[.dev0]
| TAG[.postDISTANCE[.dev0]] . | def render_pep440_old(pieces):
"""TAG[.postDISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.postDISTANCE[.dev0]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".post%d" % pie... | [
"def",
"render_pep440_old",
"(",
"pieces",
")",
":",
"if",
"pieces",
"[",
"\"closest-tag\"",
"]",
":",
"rendered",
"=",
"pieces",
"[",
"\"closest-tag\"",
"]",
"if",
"pieces",
"[",
"\"distance\"",
"]",
"or",
"pieces",
"[",
"\"dirty\"",
"]",
":",
"rendered",
... | [
1303,
0
] | [
1322,
19
] | python | en | ['en', 'mt', 'hi'] | False |
render_git_describe | (pieces) | TAG[-DISTANCE-gHEX][-dirty].
Like 'git describe --tags --dirty --always'.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
| TAG[-DISTANCE-gHEX][-dirty]. | def render_git_describe(pieces):
"""TAG[-DISTANCE-gHEX][-dirty].
Like 'git describe --tags --dirty --always'.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"]:
rendered +=... | [
"def",
"render_git_describe",
"(",
"pieces",
")",
":",
"if",
"pieces",
"[",
"\"closest-tag\"",
"]",
":",
"rendered",
"=",
"pieces",
"[",
"\"closest-tag\"",
"]",
"if",
"pieces",
"[",
"\"distance\"",
"]",
":",
"rendered",
"+=",
"\"-%d-g%s\"",
"%",
"(",
"pieces... | [
1325,
0
] | [
1342,
19
] | python | en | ['en', 'en', 'en'] | False |
render_git_describe_long | (pieces) | TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
| TAG-DISTANCE-gHEX[-dirty]. | def render_git_describe_long(pieces):
"""TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
... | [
"def",
"render_git_describe_long",
"(",
"pieces",
")",
":",
"if",
"pieces",
"[",
"\"closest-tag\"",
"]",
":",
"rendered",
"=",
"pieces",
"[",
"\"closest-tag\"",
"]",
"rendered",
"+=",
"\"-%d-g%s\"",
"%",
"(",
"pieces",
"[",
"\"distance\"",
"]",
",",
"pieces",
... | [
1345,
0
] | [
1362,
19
] | python | en | ['en', 'en', 'pt'] | False |
render | (pieces, style) | Render the given version pieces into the requested style. | Render the given version pieces into the requested style. | def render(pieces, style):
"""Render the given version pieces into the requested style."""
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"],
"date": None}
... | [
"def",
"render",
"(",
"pieces",
",",
"style",
")",
":",
"if",
"pieces",
"[",
"\"error\"",
"]",
":",
"return",
"{",
"\"version\"",
":",
"\"unknown\"",
",",
"\"full-revisionid\"",
":",
"pieces",
".",
"get",
"(",
"\"long\"",
")",
",",
"\"dirty\"",
":",
"Non... | [
1365,
0
] | [
1394,
39
] | python | en | ['en', 'en', 'en'] | True |
get_versions | (verbose=False) | Get the project version from whatever source is available.
Returns dict with two keys: 'version' and 'full'.
| Get the project version from whatever source is available. | def get_versions(verbose=False):
"""Get the project version from whatever source is available.
Returns dict with two keys: 'version' and 'full'.
"""
if "versioneer" in sys.modules:
# see the discussion in cmdclass.py:get_cmdclass()
del sys.modules["versioneer"]
root = get_root()
... | [
"def",
"get_versions",
"(",
"verbose",
"=",
"False",
")",
":",
"if",
"\"versioneer\"",
"in",
"sys",
".",
"modules",
":",
"# see the discussion in cmdclass.py:get_cmdclass()",
"del",
"sys",
".",
"modules",
"[",
"\"versioneer\"",
"]",
"root",
"=",
"get_root",
"(",
... | [
1401,
0
] | [
1474,
25
] | python | en | ['en', 'en', 'en'] | True |
get_version | () | Get the short version string for this project. | Get the short version string for this project. | def get_version():
"""Get the short version string for this project."""
return get_versions()["version"] | [
"def",
"get_version",
"(",
")",
":",
"return",
"get_versions",
"(",
")",
"[",
"\"version\"",
"]"
] | [
1477,
0
] | [
1479,
36
] | python | en | ['en', 'en', 'en'] | True |
get_cmdclass | () | Get the custom setuptools/distutils subclasses used by Versioneer. | Get the custom setuptools/distutils subclasses used by Versioneer. | def get_cmdclass():
"""Get the custom setuptools/distutils subclasses used by Versioneer."""
if "versioneer" in sys.modules:
del sys.modules["versioneer"]
# this fixes the "python setup.py develop" case (also 'install' and
# 'easy_install .'), in which subdependencies of the main project... | [
"def",
"get_cmdclass",
"(",
")",
":",
"if",
"\"versioneer\"",
"in",
"sys",
".",
"modules",
":",
"del",
"sys",
".",
"modules",
"[",
"\"versioneer\"",
"]",
"# this fixes the \"python setup.py develop\" case (also 'install' and",
"# 'easy_install .'), in which subdependencies of... | [
1482,
0
] | [
1649,
15
] | python | en | ['en', 'et', 'en'] | True |
do_setup | () | Main VCS-independent setup function for installing Versioneer. | Main VCS-independent setup function for installing Versioneer. | def do_setup():
"""Main VCS-independent setup function for installing Versioneer."""
root = get_root()
try:
cfg = get_config_from_root(root)
except (EnvironmentError, configparser.NoSectionError,
configparser.NoOptionError) as e:
if isinstance(e, (EnvironmentError, configpars... | [
"def",
"do_setup",
"(",
")",
":",
"root",
"=",
"get_root",
"(",
")",
"try",
":",
"cfg",
"=",
"get_config_from_root",
"(",
"root",
")",
"except",
"(",
"EnvironmentError",
",",
"configparser",
".",
"NoSectionError",
",",
"configparser",
".",
"NoOptionError",
"... | [
1696,
0
] | [
1775,
12
] | python | en | ['en', 'en', 'en'] | True |
scan_setup_py | () | Validate the contents of setup.py against Versioneer's expectations. | Validate the contents of setup.py against Versioneer's expectations. | def scan_setup_py():
"""Validate the contents of setup.py against Versioneer's expectations."""
found = set()
setters = False
errors = 0
with open("setup.py", "r") as f:
for line in f.readlines():
if "import versioneer" in line:
found.add("import")
if ... | [
"def",
"scan_setup_py",
"(",
")",
":",
"found",
"=",
"set",
"(",
")",
"setters",
"=",
"False",
"errors",
"=",
"0",
"with",
"open",
"(",
"\"setup.py\"",
",",
"\"r\"",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
... | [
1778,
0
] | [
1812,
17
] | python | en | ['en', 'en', 'en'] | True |
Ghostscript | (tile, size, fp, scale=1) | Render an image using Ghostscript | Render an image using Ghostscript | def Ghostscript(tile, size, fp, scale=1):
"""Render an image using Ghostscript"""
# Unpack decoder tile
decoder, tile, offset, data = tile[0]
length, bbox = data
# Hack to support hi-res rendering
scale = int(scale) or 1
# orig_size = size
# orig_bbox = bbox
size = (size[0] * scale... | [
"def",
"Ghostscript",
"(",
"tile",
",",
"size",
",",
"fp",
",",
"scale",
"=",
"1",
")",
":",
"# Unpack decoder tile",
"decoder",
",",
"tile",
",",
"offset",
",",
"data",
"=",
"tile",
"[",
"0",
"]",
"length",
",",
"bbox",
"=",
"data",
"# Hack to support... | [
63,
0
] | [
155,
13
] | python | af | ['de', 'af', 'en'] | False |
_save | (im, fp, filename, eps=1) | EPS Writer for the Python Imaging Library. | EPS Writer for the Python Imaging Library. | def _save(im, fp, filename, eps=1):
"""EPS Writer for the Python Imaging Library."""
#
# make sure image data is available
im.load()
#
# determine postscript image mode
if im.mode == "L":
operator = (8, 1, "image")
elif im.mode == "RGB":
operator = (8, 3, "false 3 color... | [
"def",
"_save",
"(",
"im",
",",
"fp",
",",
"filename",
",",
"eps",
"=",
"1",
")",
":",
"#",
"# make sure image data is available",
"im",
".",
"load",
"(",
")",
"#",
"# determine postscript image mode",
"if",
"im",
".",
"mode",
"==",
"\"L\"",
":",
"operator... | [
346,
0
] | [
405,
23
] | python | en | ['en', 'en', 'en'] | True |
_normalize_mode | (im, initial_call=False) |
Takes an image (or frame), returns an image in a mode that is appropriate
for saving in a Gif.
It may return the original image, or it may return an image converted to
palette or 'L' mode.
UNDONE: What is the point of mucking with the initial call palette, for
an image that shouldn't have a p... |
Takes an image (or frame), returns an image in a mode that is appropriate
for saving in a Gif. | def _normalize_mode(im, initial_call=False):
"""
Takes an image (or frame), returns an image in a mode that is appropriate
for saving in a Gif.
It may return the original image, or it may return an image converted to
palette or 'L' mode.
UNDONE: What is the point of mucking with the initial ca... | [
"def",
"_normalize_mode",
"(",
"im",
",",
"initial_call",
"=",
"False",
")",
":",
"if",
"im",
".",
"mode",
"in",
"RAWMODE",
":",
"im",
".",
"load",
"(",
")",
"return",
"im",
"if",
"Image",
".",
"getmodebase",
"(",
"im",
".",
"mode",
")",
"==",
"\"R... | [
325,
0
] | [
352,
26
] | python | en | ['en', 'error', 'th'] | False |
_normalize_palette | (im, palette, info) |
Normalizes the palette for image.
- Sets the palette to the incoming palette, if provided.
- Ensures that there's a palette for L mode images
- Optimizes the palette if necessary/desired.
:param im: Image object
:param palette: bytes object containing the source palette, or ....
:par... |
Normalizes the palette for image.
- Sets the palette to the incoming palette, if provided.
- Ensures that there's a palette for L mode images
- Optimizes the palette if necessary/desired. | def _normalize_palette(im, palette, info):
"""
Normalizes the palette for image.
- Sets the palette to the incoming palette, if provided.
- Ensures that there's a palette for L mode images
- Optimizes the palette if necessary/desired.
:param im: Image object
:param palette: bytes obje... | [
"def",
"_normalize_palette",
"(",
"im",
",",
"palette",
",",
"info",
")",
":",
"source_palette",
"=",
"None",
"if",
"palette",
":",
"# a bytes palette",
"if",
"isinstance",
"(",
"palette",
",",
"(",
"bytes",
",",
"bytearray",
",",
"list",
")",
")",
":",
... | [
355,
0
] | [
396,
13
] | python | en | ['en', 'error', 'th'] | False |
_get_optimize | (im, info) |
Palette optimization is a potentially expensive operation.
This function determines if the palette should be optimized using
some heuristics, then returns the list of palette entries in use.
:param im: Image object
:param info: encoderinfo
:returns: list of indexes of palette entries in use, ... |
Palette optimization is a potentially expensive operation. | def _get_optimize(im, info):
"""
Palette optimization is a potentially expensive operation.
This function determines if the palette should be optimized using
some heuristics, then returns the list of palette entries in use.
:param im: Image object
:param info: encoderinfo
:returns: list of... | [
"def",
"_get_optimize",
"(",
"im",
",",
"info",
")",
":",
"if",
"im",
".",
"mode",
"in",
"(",
"\"P\"",
",",
"\"L\"",
")",
"and",
"info",
"and",
"info",
".",
"get",
"(",
"\"optimize\"",
",",
"0",
")",
":",
"# Potentially expensive operation.",
"# The pale... | [
665,
0
] | [
699,
42
] | python | en | ['en', 'error', 'th'] | False |
_get_header_palette | (palette_bytes) |
Returns the palette, null padded to the next power of 2 (*3) bytes
suitable for direct inclusion in the GIF header
:param palette_bytes: Unpadded palette bytes, in RGBRGB form
:returns: Null padded palette
|
Returns the palette, null padded to the next power of 2 (*3) bytes
suitable for direct inclusion in the GIF header | def _get_header_palette(palette_bytes):
"""
Returns the palette, null padded to the next power of 2 (*3) bytes
suitable for direct inclusion in the GIF header
:param palette_bytes: Unpadded palette bytes, in RGBRGB form
:returns: Null padded palette
"""
color_table_size = _get_color_table_s... | [
"def",
"_get_header_palette",
"(",
"palette_bytes",
")",
":",
"color_table_size",
"=",
"_get_color_table_size",
"(",
"palette_bytes",
")",
"# add the missing amount of bytes",
"# the palette has to be 2<<n in size",
"actual_target_size_diff",
"=",
"(",
"2",
"<<",
"color_table_s... | [
712,
0
] | [
727,
24
] | python | en | ['en', 'error', 'th'] | False |
_get_palette_bytes | (im) |
Gets the palette for inclusion in the gif header
:param im: Image object
:returns: Bytes, len<=768 suitable for inclusion in gif header
|
Gets the palette for inclusion in the gif header | def _get_palette_bytes(im):
"""
Gets the palette for inclusion in the gif header
:param im: Image object
:returns: Bytes, len<=768 suitable for inclusion in gif header
"""
return im.palette.palette | [
"def",
"_get_palette_bytes",
"(",
"im",
")",
":",
"return",
"im",
".",
"palette",
".",
"palette"
] | [
730,
0
] | [
737,
29
] | python | en | ['en', 'error', 'th'] | False |
_get_global_header | (im, info) | Return a list of strings representing a GIF header | Return a list of strings representing a GIF header | def _get_global_header(im, info):
"""Return a list of strings representing a GIF header"""
# Header Block
# http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp
version = b"87a"
for extensionKey in ["transparency", "duration", "loop", "comment"]:
if info and extensionKey in ... | [
"def",
"_get_global_header",
"(",
"im",
",",
"info",
")",
":",
"# Header Block",
"# http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp",
"version",
"=",
"b\"87a\"",
"for",
"extensionKey",
"in",
"[",
"\"transparency\"",
",",
"\"duration\"",
",",
"\"loop\"",
... | [
752,
0
] | [
788,
5
] | python | en | ['en', 'en', 'en'] | True |
getheader | (im, palette=None, info=None) |
Legacy Method to get Gif data from image.
Warning:: May modify image data.
:param im: Image object
:param palette: bytes object containing the source palette, or ....
:param info: encoderinfo
:returns: tuple of(list of header items, optimized palette)
|
Legacy Method to get Gif data from image. | def getheader(im, palette=None, info=None):
"""
Legacy Method to get Gif data from image.
Warning:: May modify image data.
:param im: Image object
:param palette: bytes object containing the source palette, or ....
:param info: encoderinfo
:returns: tuple of(list of header items, optimized... | [
"def",
"getheader",
"(",
"im",
",",
"palette",
"=",
"None",
",",
"info",
"=",
"None",
")",
":",
"used_palette_colors",
"=",
"_get_optimize",
"(",
"im",
",",
"info",
")",
"if",
"info",
"is",
"None",
":",
"info",
"=",
"{",
"}",
"if",
"\"background\"",
... | [
811,
0
] | [
836,
38
] | python | en | ['en', 'error', 'th'] | False |
getdata | (im, offset=(0, 0), **params) |
Legacy Method
Return a list of strings representing this image.
The first string is a local image header, the rest contains
encoded image data.
:param im: Image object
:param offset: Tuple of (x, y) pixels. Defaults to (0,0)
:param \\**params: E.g. duration or other encoder info parameter... |
Legacy Method | def getdata(im, offset=(0, 0), **params):
"""
Legacy Method
Return a list of strings representing this image.
The first string is a local image header, the rest contains
encoded image data.
:param im: Image object
:param offset: Tuple of (x, y) pixels. Defaults to (0,0)
:param \\**para... | [
"def",
"getdata",
"(",
"im",
",",
"offset",
"=",
"(",
"0",
",",
"0",
")",
",",
"*",
"*",
"params",
")",
":",
"class",
"Collector",
":",
"data",
"=",
"[",
"]",
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"data",
".",
"appe... | [
841,
0
] | [
868,
18
] | python | en | ['en', 'error', 'th'] | False |
SessionStore._key_to_file | (self, session_key=None) |
Get the file associated with this session key.
|
Get the file associated with this session key.
| def _key_to_file(self, session_key=None):
"""
Get the file associated with this session key.
"""
if session_key is None:
session_key = self._get_or_create_session_key()
# Make sure we're not vulnerable to directory traversal. Session keys
# should always be m... | [
"def",
"_key_to_file",
"(",
"self",
",",
"session_key",
"=",
"None",
")",
":",
"if",
"session_key",
"is",
"None",
":",
"session_key",
"=",
"self",
".",
"_get_or_create_session_key",
"(",
")",
"# Make sure we're not vulnerable to directory traversal. Session keys",
"# sh... | [
44,
4
] | [
58,
78
] | python | en | ['en', 'error', 'th'] | False |
SessionStore._last_modification | (self) |
Return the modification time of the file storing the session's content.
|
Return the modification time of the file storing the session's content.
| def _last_modification(self):
"""
Return the modification time of the file storing the session's content.
"""
modification = os.stat(self._key_to_file()).st_mtime
if settings.USE_TZ:
modification = datetime.datetime.utcfromtimestamp(modification)
modificat... | [
"def",
"_last_modification",
"(",
"self",
")",
":",
"modification",
"=",
"os",
".",
"stat",
"(",
"self",
".",
"_key_to_file",
"(",
")",
")",
".",
"st_mtime",
"if",
"settings",
".",
"USE_TZ",
":",
"modification",
"=",
"datetime",
".",
"datetime",
".",
"ut... | [
60,
4
] | [
70,
27
] | python | en | ['en', 'error', 'th'] | False |
no_template_view | (request) | A simple view that expects a GET request, and returns a rendered template | A simple view that expects a GET request, and returns a rendered template | def no_template_view(request):
"A simple view that expects a GET request, and returns a rendered template"
return HttpResponse("No template used. Sample content: twice once twice. Content ends.") | [
"def",
"no_template_view",
"(",
"request",
")",
":",
"return",
"HttpResponse",
"(",
"\"No template used. Sample content: twice once twice. Content ends.\"",
")"
] | [
19,
0
] | [
21,
92
] | python | en | ['en', 'en', 'en'] | True |
staff_only_view | (request) | A view that can only be visited by staff. Non staff members get an exception | A view that can only be visited by staff. Non staff members get an exception | def staff_only_view(request):
"A view that can only be visited by staff. Non staff members get an exception"
if request.user.is_staff:
return HttpResponse('')
else:
raise CustomTestException() | [
"def",
"staff_only_view",
"(",
"request",
")",
":",
"if",
"request",
".",
"user",
".",
"is_staff",
":",
"return",
"HttpResponse",
"(",
"''",
")",
"else",
":",
"raise",
"CustomTestException",
"(",
")"
] | [
24,
0
] | [
29,
35
] | python | en | ['en', 'en', 'en'] | True |
get_view | (request) | A simple login protected view | A simple login protected view | def get_view(request):
"A simple login protected view"
return HttpResponse("Hello world") | [
"def",
"get_view",
"(",
"request",
")",
":",
"return",
"HttpResponse",
"(",
"\"Hello world\"",
")"
] | [
32,
0
] | [
34,
38
] | python | en | ['es', 'en', 'en'] | True |
request_data | (request, template='base.html', data='sausage') | A simple view that returns the request data in the context | A simple view that returns the request data in the context | def request_data(request, template='base.html', data='sausage'):
"A simple view that returns the request data in the context"
# request.REQUEST is deprecated, but needs testing until removed.
with warnings.catch_warnings(record=True):
warnings.simplefilter("always")
request_foo = request.RE... | [
"def",
"request_data",
"(",
"request",
",",
"template",
"=",
"'base.html'",
",",
"data",
"=",
"'sausage'",
")",
":",
"# request.REQUEST is deprecated, but needs testing until removed.",
"with",
"warnings",
".",
"catch_warnings",
"(",
"record",
"=",
"True",
")",
":",
... | [
38,
0
] | [
55,
6
] | python | en | ['en', 'en', 'en'] | True |
view_with_argument | (request, name) | A view that takes a string argument
The purpose of this view is to check that if a space is provided in
the argument, the test framework unescapes the %20 before passing
the value to the view.
| A view that takes a string argument | def view_with_argument(request, name):
"""A view that takes a string argument
The purpose of this view is to check that if a space is provided in
the argument, the test framework unescapes the %20 before passing
the value to the view.
"""
if name == 'Arthur Dent':
return HttpResponse('H... | [
"def",
"view_with_argument",
"(",
"request",
",",
"name",
")",
":",
"if",
"name",
"==",
"'Arthur Dent'",
":",
"return",
"HttpResponse",
"(",
"'Hi, Arthur'",
")",
"else",
":",
"return",
"HttpResponse",
"(",
"'Howdy, %s'",
"%",
"name",
")"
] | [
58,
0
] | [
68,
47
] | python | en | ['en', 'en', 'en'] | True |
nested_view | (request) |
A view that uses test client to call another view.
|
A view that uses test client to call another view.
| def nested_view(request):
"""
A view that uses test client to call another view.
"""
setup_test_environment()
c = Client()
c.get("/no_template_view")
return render_to_response('base.html', {'nested': 'yes'}) | [
"def",
"nested_view",
"(",
"request",
")",
":",
"setup_test_environment",
"(",
")",
"c",
"=",
"Client",
"(",
")",
"c",
".",
"get",
"(",
"\"/no_template_view\"",
")",
"return",
"render_to_response",
"(",
"'base.html'",
",",
"{",
"'nested'",
":",
"'yes'",
"}",... | [
71,
0
] | [
78,
61
] | python | en | ['en', 'error', 'th'] | False |
login_protected_redirect_view | (request) | A view that redirects all requests to the GET view | A view that redirects all requests to the GET view | def login_protected_redirect_view(request):
"A view that redirects all requests to the GET view"
return HttpResponseRedirect('/get_view/') | [
"def",
"login_protected_redirect_view",
"(",
"request",
")",
":",
"return",
"HttpResponseRedirect",
"(",
"'/get_view/'",
")"
] | [
81,
0
] | [
83,
45
] | python | en | ['en', 'en', 'en'] | True |
set_session_view | (request) | A view that sets a session variable | A view that sets a session variable | def set_session_view(request):
"A view that sets a session variable"
request.session['session_var'] = 'YES'
return HttpResponse('set_session') | [
"def",
"set_session_view",
"(",
"request",
")",
":",
"request",
".",
"session",
"[",
"'session_var'",
"]",
"=",
"'YES'",
"return",
"HttpResponse",
"(",
"'set_session'",
")"
] | [
87,
0
] | [
90,
38
] | python | en | ['en', 'en', 'en'] | True |
check_session_view | (request) | A view that reads a session variable | A view that reads a session variable | def check_session_view(request):
"A view that reads a session variable"
return HttpResponse(request.session.get('session_var', 'NO')) | [
"def",
"check_session_view",
"(",
"request",
")",
":",
"return",
"HttpResponse",
"(",
"request",
".",
"session",
".",
"get",
"(",
"'session_var'",
",",
"'NO'",
")",
")"
] | [
93,
0
] | [
95,
65
] | python | en | ['en', 'en', 'en'] | True |
request_methods_view | (request) | A view that responds with the request method | A view that responds with the request method | def request_methods_view(request):
"A view that responds with the request method"
return HttpResponse('request method: %s' % request.method) | [
"def",
"request_methods_view",
"(",
"request",
")",
":",
"return",
"HttpResponse",
"(",
"'request method: %s'",
"%",
"request",
".",
"method",
")"
] | [
98,
0
] | [
100,
62
] | python | en | ['en', 'en', 'en'] | True |
return_json_file | (request) | A view that parses and returns a JSON string as a file. | A view that parses and returns a JSON string as a file. | def return_json_file(request):
"A view that parses and returns a JSON string as a file."
match = CONTENT_TYPE_RE.match(request.META['CONTENT_TYPE'])
if match:
charset = match.group(1)
else:
charset = settings.DEFAULT_CHARSET
# This just checks that the uploaded data is JSON
obj_... | [
"def",
"return_json_file",
"(",
"request",
")",
":",
"match",
"=",
"CONTENT_TYPE_RE",
".",
"match",
"(",
"request",
".",
"META",
"[",
"'CONTENT_TYPE'",
"]",
")",
"if",
"match",
":",
"charset",
"=",
"match",
".",
"group",
"(",
"1",
")",
"else",
":",
"ch... | [
113,
0
] | [
127,
19
] | python | en | ['en', 'en', 'en'] | True |
check_headers | (request) | A view that responds with value of the X-ARG-CHECK header | A view that responds with value of the X-ARG-CHECK header | def check_headers(request):
"A view that responds with value of the X-ARG-CHECK header"
return HttpResponse('HTTP_X_ARG_CHECK: %s' % request.META.get('HTTP_X_ARG_CHECK', 'Undefined')) | [
"def",
"check_headers",
"(",
"request",
")",
":",
"return",
"HttpResponse",
"(",
"'HTTP_X_ARG_CHECK: %s'",
"%",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_X_ARG_CHECK'",
",",
"'Undefined'",
")",
")"
] | [
130,
0
] | [
132,
99
] | python | en | ['en', 'en', 'en'] | True |
body | (request) | A view that is requested with GET and accesses request.body. Refs #14753. | A view that is requested with GET and accesses request.body. Refs #14753. | def body(request):
"A view that is requested with GET and accesses request.body. Refs #14753."
return HttpResponse(request.body) | [
"def",
"body",
"(",
"request",
")",
":",
"return",
"HttpResponse",
"(",
"request",
".",
"body",
")"
] | [
135,
0
] | [
137,
37
] | python | en | ['en', 'en', 'en'] | True |
read_all | (request) | A view that is requested with accesses request.read(). | A view that is requested with accesses request.read(). | def read_all(request):
"A view that is requested with accesses request.read()."
return HttpResponse(request.read()) | [
"def",
"read_all",
"(",
"request",
")",
":",
"return",
"HttpResponse",
"(",
"request",
".",
"read",
"(",
")",
")"
] | [
140,
0
] | [
142,
39
] | python | en | ['en', 'en', 'en'] | True |
read_buffer | (request) | A view that is requested with accesses request.read(LARGE_BUFFER). | A view that is requested with accesses request.read(LARGE_BUFFER). | def read_buffer(request):
"A view that is requested with accesses request.read(LARGE_BUFFER)."
return HttpResponse(request.read(99999)) | [
"def",
"read_buffer",
"(",
"request",
")",
":",
"return",
"HttpResponse",
"(",
"request",
".",
"read",
"(",
"99999",
")",
")"
] | [
145,
0
] | [
147,
44
] | python | en | ['en', 'en', 'en'] | True |
render_template_multiple_times | (request) | A view that renders a template multiple times. | A view that renders a template multiple times. | def render_template_multiple_times(request):
"""A view that renders a template multiple times."""
return HttpResponse(
render_to_string('base.html') + render_to_string('base.html')) | [
"def",
"render_template_multiple_times",
"(",
"request",
")",
":",
"return",
"HttpResponse",
"(",
"render_to_string",
"(",
"'base.html'",
")",
"+",
"render_to_string",
"(",
"'base.html'",
")",
")"
] | [
156,
0
] | [
159,
70
] | python | en | ['en', 'en', 'en'] | True |
Command.get_input_data | (self, field, message, default=None) |
Override this method if you want to customize data inputs or
validation exceptions.
|
Override this method if you want to customize data inputs or
validation exceptions.
| def get_input_data(self, field, message, default=None):
"""
Override this method if you want to customize data inputs or
validation exceptions.
"""
raw_value = input(message)
if default and raw_value == '':
raw_value = default
try:
val = fi... | [
"def",
"get_input_data",
"(",
"self",
",",
"field",
",",
"message",
",",
"default",
"=",
"None",
")",
":",
"raw_value",
"=",
"input",
"(",
"message",
")",
"if",
"default",
"and",
"raw_value",
"==",
"''",
":",
"raw_value",
"=",
"default",
"try",
":",
"v... | [
152,
4
] | [
166,
18
] | python | en | ['en', 'error', 'th'] | False |
StateTests.test_create | (self) |
Tests making a ProjectState from an Apps
|
Tests making a ProjectState from an Apps
| def test_create(self):
"""
Tests making a ProjectState from an Apps
"""
new_apps = Apps(["migrations"])
class Author(models.Model):
name = models.CharField(max_length=255)
bio = models.TextField()
age = models.IntegerField(blank=True, null=Tr... | [
"def",
"test_create",
"(",
"self",
")",
":",
"new_apps",
"=",
"Apps",
"(",
"[",
"\"migrations\"",
"]",
")",
"class",
"Author",
"(",
"models",
".",
"Model",
")",
":",
"name",
"=",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"255",
")",
"bio",
... | [
13,
4
] | [
89,
73
] | python | en | ['en', 'error', 'th'] | False |
StateTests.test_render | (self) |
Tests rendering a ProjectState into an Apps.
|
Tests rendering a ProjectState into an Apps.
| def test_render(self):
"""
Tests rendering a ProjectState into an Apps.
"""
project_state = ProjectState()
project_state.add_model_state(ModelState(
"migrations",
"Tag",
[
("id", models.AutoField(primary_key=True)),
... | [
"def",
"test_render",
"(",
"self",
")",
":",
"project_state",
"=",
"ProjectState",
"(",
")",
"project_state",
".",
"add_model_state",
"(",
"ModelState",
"(",
"\"migrations\"",
",",
"\"Tag\"",
",",
"[",
"(",
"\"id\"",
",",
"models",
".",
"AutoField",
"(",
"pr... | [
91,
4
] | [
127,
95
] | python | en | ['en', 'error', 'th'] | False |
StateTests.test_render_project_dependencies | (self) |
Tests that the ProjectState render method correctly renders models
to account for inter-model base dependencies.
|
Tests that the ProjectState render method correctly renders models
to account for inter-model base dependencies.
| def test_render_project_dependencies(self):
"""
Tests that the ProjectState render method correctly renders models
to account for inter-model base dependencies.
"""
new_apps = Apps()
class A(models.Model):
class Meta:
app_label = "migrations"
... | [
"def",
"test_render_project_dependencies",
"(",
"self",
")",
":",
"new_apps",
"=",
"Apps",
"(",
")",
"class",
"A",
"(",
"models",
".",
"Model",
")",
":",
"class",
"Meta",
":",
"app_label",
"=",
"\"migrations\"",
"apps",
"=",
"new_apps",
"class",
"B",
"(",
... | [
197,
4
] | [
254,
34
] | python | en | ['en', 'error', 'th'] | False |
StateTests.test_render_unique_app_labels | (self) |
Tests that the ProjectState render method doesn't raise an
ImproperlyConfigured exception about unique labels if two dotted app
names have the same last part.
|
Tests that the ProjectState render method doesn't raise an
ImproperlyConfigured exception about unique labels if two dotted app
names have the same last part.
| def test_render_unique_app_labels(self):
"""
Tests that the ProjectState render method doesn't raise an
ImproperlyConfigured exception about unique labels if two dotted app
names have the same last part.
"""
class A(models.Model):
class Meta:
a... | [
"def",
"test_render_unique_app_labels",
"(",
"self",
")",
":",
"class",
"A",
"(",
"models",
".",
"Model",
")",
":",
"class",
"Meta",
":",
"app_label",
"=",
"\"django.contrib.auth\"",
"class",
"B",
"(",
"models",
".",
"Model",
")",
":",
"class",
"Meta",
":"... | [
256,
4
] | [
275,
57
] | python | en | ['en', 'error', 'th'] | False |
StateTests.test_equality | (self) |
Tests that == and != are implemented correctly.
|
Tests that == and != are implemented correctly.
| def test_equality(self):
"""
Tests that == and != are implemented correctly.
"""
# Test two things that should be equal
project_state = ProjectState()
project_state.add_model_state(ModelState(
"migrations",
"Tag",
[
("i... | [
"def",
"test_equality",
"(",
"self",
")",
":",
"# Test two things that should be equal",
"project_state",
"=",
"ProjectState",
"(",
")",
"project_state",
".",
"add_model_state",
"(",
"ModelState",
"(",
"\"migrations\"",
",",
"\"Tag\"",
",",
"[",
"(",
"\"id\"",
",",
... | [
277,
4
] | [
315,
61
] | python | en | ['en', 'error', 'th'] | False |
StateTests.test_real_apps | (self) |
Tests that including real apps can resolve dangling FK errors.
This test relies on the fact that contenttypes is always loaded.
|
Tests that including real apps can resolve dangling FK errors.
This test relies on the fact that contenttypes is always loaded.
| def test_real_apps(self):
"""
Tests that including real apps can resolve dangling FK errors.
This test relies on the fact that contenttypes is always loaded.
"""
new_apps = Apps()
class TestModel(models.Model):
ct = models.ForeignKey("contenttypes.ContentType... | [
"def",
"test_real_apps",
"(",
"self",
")",
":",
"new_apps",
"=",
"Apps",
"(",
")",
"class",
"TestModel",
"(",
"models",
".",
"Model",
")",
":",
"ct",
"=",
"models",
".",
"ForeignKey",
"(",
"\"contenttypes.ContentType\"",
")",
"class",
"Meta",
":",
"app_lab... | [
361,
4
] | [
388,
9
] | python | en | ['en', 'error', 'th'] | False |
StateTests.test_ignore_order_wrt | (self) |
Makes sure ProjectState doesn't include OrderWrt fields when
making from existing models.
|
Makes sure ProjectState doesn't include OrderWrt fields when
making from existing models.
| def test_ignore_order_wrt(self):
"""
Makes sure ProjectState doesn't include OrderWrt fields when
making from existing models.
"""
new_apps = Apps()
class Author(models.Model):
name = models.TextField()
class Meta:
app_label = "mi... | [
"def",
"test_ignore_order_wrt",
"(",
"self",
")",
":",
"new_apps",
"=",
"Apps",
"(",
")",
"class",
"Author",
"(",
"models",
".",
"Model",
")",
":",
"name",
"=",
"models",
".",
"TextField",
"(",
")",
"class",
"Meta",
":",
"app_label",
"=",
"\"migrations\"... | [
390,
4
] | [
419,
9
] | python | en | ['en', 'error', 'th'] | False |
ModelStateTests.test_fields_immutability | (self) |
Tests that rendering a model state doesn't alter its internal fields.
|
Tests that rendering a model state doesn't alter its internal fields.
| def test_fields_immutability(self):
"""
Tests that rendering a model state doesn't alter its internal fields.
"""
apps = Apps()
field = models.CharField(max_length=1)
state = ModelState('app', 'Model', [('name', field)])
Model = state.render(apps)
self.ass... | [
"def",
"test_fields_immutability",
"(",
"self",
")",
":",
"apps",
"=",
"Apps",
"(",
")",
"field",
"=",
"models",
".",
"CharField",
"(",
"max_length",
"=",
"1",
")",
"state",
"=",
"ModelState",
"(",
"'app'",
",",
"'Model'",
",",
"[",
"(",
"'name'",
",",... | [
434,
4
] | [
442,
65
] | python | en | ['en', 'error', 'th'] | False |
precision_wkt | (geom, prec) |
Returns WKT text of the geometry according to the given precision (an
integer or a string). If the precision is an integer, then the decimal
places of coordinates WKT will be truncated to that number:
>>> from django.contrib.gis.geos import Point
>>> pnt = Point(5, 23)
>>> pnt.wkt
'PO... |
Returns WKT text of the geometry according to the given precision (an
integer or a string). If the precision is an integer, then the decimal
places of coordinates WKT will be truncated to that number: | def precision_wkt(geom, prec):
"""
Returns WKT text of the geometry according to the given precision (an
integer or a string). If the precision is an integer, then the decimal
places of coordinates WKT will be truncated to that number:
>>> from django.contrib.gis.geos import Point
>>> pnt = ... | [
"def",
"precision_wkt",
"(",
"geom",
",",
"prec",
")",
":",
"if",
"isinstance",
"(",
"prec",
",",
"int",
")",
":",
"num_fmt",
"=",
"'%%.%df'",
"%",
"prec",
"elif",
"isinstance",
"(",
"prec",
",",
"six",
".",
"string_types",
")",
":",
"num_fmt",
"=",
... | [
7,
0
] | [
58,
55
] | python | en | ['en', 'error', 'th'] | False |
ApplicationCommunicator.wait | (self, timeout=1) |
Waits for the application to stop itself and returns any exceptions.
|
Waits for the application to stop itself and returns any exceptions.
| async def wait(self, timeout=1):
"""
Waits for the application to stop itself and returns any exceptions.
"""
try:
async with async_timeout(timeout):
try:
await self.future
self.future.result()
except asy... | [
"async",
"def",
"wait",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"try",
":",
"async",
"with",
"async_timeout",
"(",
"timeout",
")",
":",
"try",
":",
"await",
"self",
".",
"future",
"self",
".",
"future",
".",
"result",
"(",
")",
"except",
"... | [
22,
4
] | [
39,
24
] | python | en | ['en', 'error', 'th'] | False |
ApplicationCommunicator.send_input | (self, message) |
Sends a single message to the application
|
Sends a single message to the application
| async def send_input(self, message):
"""
Sends a single message to the application
"""
# Give it the message
await self.input_queue.put(message) | [
"async",
"def",
"send_input",
"(",
"self",
",",
"message",
")",
":",
"# Give it the message",
"await",
"self",
".",
"input_queue",
".",
"put",
"(",
"message",
")"
] | [
56,
4
] | [
61,
43
] | python | en | ['en', 'error', 'th'] | False |
ApplicationCommunicator.receive_output | (self, timeout=1) |
Receives a single message from the application, with optional timeout.
|
Receives a single message from the application, with optional timeout.
| async def receive_output(self, timeout=1):
"""
Receives a single message from the application, with optional timeout.
"""
# Make sure there's not an exception to raise from the task
if self.future.done():
self.future.result()
# Wait and receive the message
... | [
"async",
"def",
"receive_output",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"# Make sure there's not an exception to raise from the task",
"if",
"self",
".",
"future",
".",
"done",
"(",
")",
":",
"self",
".",
"future",
".",
"result",
"(",
")",
"# Wait a... | [
63,
4
] | [
84,
19
] | python | en | ['en', 'error', 'th'] | False |
ApplicationCommunicator.receive_nothing | (self, timeout=0.1, interval=0.01) |
Checks that there is no message to receive in the given time.
|
Checks that there is no message to receive in the given time.
| async def receive_nothing(self, timeout=0.1, interval=0.01):
"""
Checks that there is no message to receive in the given time.
"""
# `interval` has precedence over `timeout`
start = time.monotonic()
while time.monotonic() - start < timeout:
if not self.output_... | [
"async",
"def",
"receive_nothing",
"(",
"self",
",",
"timeout",
"=",
"0.1",
",",
"interval",
"=",
"0.01",
")",
":",
"# `interval` has precedence over `timeout`",
"start",
"=",
"time",
".",
"monotonic",
"(",
")",
"while",
"time",
".",
"monotonic",
"(",
")",
"... | [
86,
4
] | [
96,
40
] | python | en | ['en', 'error', 'th'] | False |
convert_exception_to_response | (get_response) |
Wrap the given get_response callable in exception-to-response conversion.
All exceptions will be converted. All known 4xx exceptions (Http404,
PermissionDenied, MultiPartParserError, SuspiciousOperation) will be
converted to the appropriate response, and all other exceptions will be
converted to 5... |
Wrap the given get_response callable in exception-to-response conversion. | def convert_exception_to_response(get_response):
"""
Wrap the given get_response callable in exception-to-response conversion.
All exceptions will be converted. All known 4xx exceptions (Http404,
PermissionDenied, MultiPartParserError, SuspiciousOperation) will be
converted to the appropriate respo... | [
"def",
"convert_exception_to_response",
"(",
"get_response",
")",
":",
"@",
"wraps",
"(",
"get_response",
")",
"def",
"inner",
"(",
"request",
")",
":",
"try",
":",
"response",
"=",
"get_response",
"(",
"request",
")",
"except",
"Exception",
"as",
"exc",
":"... | [
17,
0
] | [
37,
16
] | python | en | ['en', 'error', 'th'] | False |
handle_uncaught_exception | (request, resolver, exc_info) |
Processing for any otherwise uncaught exceptions (those that will
generate HTTP 500 responses).
|
Processing for any otherwise uncaught exceptions (those that will
generate HTTP 500 responses).
| def handle_uncaught_exception(request, resolver, exc_info):
"""
Processing for any otherwise uncaught exceptions (those that will
generate HTTP 500 responses).
"""
if settings.DEBUG_PROPAGATE_EXCEPTIONS:
raise
if settings.DEBUG:
return debug.technical_500_response(request, *exc_... | [
"def",
"handle_uncaught_exception",
"(",
"request",
",",
"resolver",
",",
"exc_info",
")",
":",
"if",
"settings",
".",
"DEBUG_PROPAGATE_EXCEPTIONS",
":",
"raise",
"if",
"settings",
".",
"DEBUG",
":",
"return",
"debug",
".",
"technical_500_response",
"(",
"request"... | [
115,
0
] | [
128,
42
] | python | en | ['en', 'error', 'th'] | False |
add_stderr_logger | (level=logging.DEBUG) |
Helper for quickly adding a StreamHandler to the logger. Useful for
debugging.
Returns the handler after adding it.
|
Helper for quickly adding a StreamHandler to the logger. Useful for
debugging. | def add_stderr_logger(level=logging.DEBUG):
"""
Helper for quickly adding a StreamHandler to the logger. Useful for
debugging.
Returns the handler after adding it.
"""
# This method needs to be in this __init__.py to get the __name__ correct
# even if urllib3 is vendored within another pack... | [
"def",
"add_stderr_logger",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"# This method needs to be in this __init__.py to get the __name__ correct",
"# even if urllib3 is vendored within another package.",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
"... | [
46,
0
] | [
61,
18
] | python | en | ['en', 'error', 'th'] | False |
disable_warnings | (category=exceptions.HTTPWarning) |
Helper for quickly disabling all urllib3 warnings.
|
Helper for quickly disabling all urllib3 warnings.
| def disable_warnings(category=exceptions.HTTPWarning):
"""
Helper for quickly disabling all urllib3 warnings.
"""
warnings.simplefilter("ignore", category) | [
"def",
"disable_warnings",
"(",
"category",
"=",
"exceptions",
".",
"HTTPWarning",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
",",
"category",
")"
] | [
81,
0
] | [
85,
45
] | python | en | ['en', 'error', 'th'] | False |
check_module | (feature) |
Checks if a module is available.
:param feature: The module to check for.
:returns: ``True`` if available, ``False`` otherwise.
:raises ValueError: If the module is not defined in this version of Pillow.
|
Checks if a module is available. | def check_module(feature):
"""
Checks if a module is available.
:param feature: The module to check for.
:returns: ``True`` if available, ``False`` otherwise.
:raises ValueError: If the module is not defined in this version of Pillow.
"""
if not (feature in modules):
raise ValueErro... | [
"def",
"check_module",
"(",
"feature",
")",
":",
"if",
"not",
"(",
"feature",
"in",
"modules",
")",
":",
"raise",
"ValueError",
"(",
"\"Unknown module %s\"",
"%",
"feature",
")",
"module",
",",
"ver",
"=",
"modules",
"[",
"feature",
"]",
"try",
":",
"__i... | [
18,
0
] | [
35,
20
] | python | en | ['en', 'error', 'th'] | False |
version_module | (feature) |
:param feature: The module to check for.
:returns:
The loaded version number as a string, or ``None`` if unknown or not available.
:raises ValueError: If the module is not defined in this version of Pillow.
|
:param feature: The module to check for.
:returns:
The loaded version number as a string, or ``None`` if unknown or not available.
:raises ValueError: If the module is not defined in this version of Pillow.
| def version_module(feature):
"""
:param feature: The module to check for.
:returns:
The loaded version number as a string, or ``None`` if unknown or not available.
:raises ValueError: If the module is not defined in this version of Pillow.
"""
if not check_module(feature):
return... | [
"def",
"version_module",
"(",
"feature",
")",
":",
"if",
"not",
"check_module",
"(",
"feature",
")",
":",
"return",
"None",
"module",
",",
"ver",
"=",
"modules",
"[",
"feature",
"]",
"if",
"ver",
"is",
"None",
":",
"return",
"None",
"return",
"getattr",
... | [
38,
0
] | [
53,
59
] | python | en | ['en', 'error', 'th'] | False |
get_supported_modules | () |
:returns: A list of all supported modules.
|
:returns: A list of all supported modules.
| def get_supported_modules():
"""
:returns: A list of all supported modules.
"""
return [f for f in modules if check_module(f)] | [
"def",
"get_supported_modules",
"(",
")",
":",
"return",
"[",
"f",
"for",
"f",
"in",
"modules",
"if",
"check_module",
"(",
"f",
")",
"]"
] | [
56,
0
] | [
60,
50
] | python | en | ['en', 'error', 'th'] | False |
check_codec | (feature) |
Checks if a codec is available.
:param feature: The codec to check for.
:returns: ``True`` if available, ``False`` otherwise.
:raises ValueError: If the codec is not defined in this version of Pillow.
|
Checks if a codec is available. | def check_codec(feature):
"""
Checks if a codec is available.
:param feature: The codec to check for.
:returns: ``True`` if available, ``False`` otherwise.
:raises ValueError: If the codec is not defined in this version of Pillow.
"""
if feature not in codecs:
raise ValueError("Unkn... | [
"def",
"check_codec",
"(",
"feature",
")",
":",
"if",
"feature",
"not",
"in",
"codecs",
":",
"raise",
"ValueError",
"(",
"\"Unknown codec %s\"",
"%",
"feature",
")",
"codec",
",",
"lib",
"=",
"codecs",
"[",
"feature",
"]",
"return",
"codec",
"+",
"\"_encod... | [
71,
0
] | [
84,
48
] | python | en | ['en', 'error', 'th'] | False |
version_codec | (feature) |
:param feature: The codec to check for.
:returns:
The version number as a string, or ``None`` if not available.
Checked at compile time for ``jpg``, run-time otherwise.
:raises ValueError: If the codec is not defined in this version of Pillow.
|
:param feature: The codec to check for.
:returns:
The version number as a string, or ``None`` if not available.
Checked at compile time for ``jpg``, run-time otherwise.
:raises ValueError: If the codec is not defined in this version of Pillow.
| def version_codec(feature):
"""
:param feature: The codec to check for.
:returns:
The version number as a string, or ``None`` if not available.
Checked at compile time for ``jpg``, run-time otherwise.
:raises ValueError: If the codec is not defined in this version of Pillow.
"""
... | [
"def",
"version_codec",
"(",
"feature",
")",
":",
"if",
"not",
"check_codec",
"(",
"feature",
")",
":",
"return",
"None",
"codec",
",",
"lib",
"=",
"codecs",
"[",
"feature",
"]",
"version",
"=",
"getattr",
"(",
"Image",
".",
"core",
",",
"lib",
"+",
... | [
87,
0
] | [
105,
18
] | python | en | ['en', 'error', 'th'] | False |
get_supported_codecs | () |
:returns: A list of all supported codecs.
|
:returns: A list of all supported codecs.
| def get_supported_codecs():
"""
:returns: A list of all supported codecs.
"""
return [f for f in codecs if check_codec(f)] | [
"def",
"get_supported_codecs",
"(",
")",
":",
"return",
"[",
"f",
"for",
"f",
"in",
"codecs",
"if",
"check_codec",
"(",
"f",
")",
"]"
] | [
108,
0
] | [
112,
48
] | python | en | ['en', 'error', 'th'] | False |
check_feature | (feature) |
Checks if a feature is available.
:param feature: The feature to check for.
:returns: ``True`` if available, ``False`` if unavailable, ``None`` if unknown.
:raises ValueError: If the feature is not defined in this version of Pillow.
|
Checks if a feature is available. | def check_feature(feature):
"""
Checks if a feature is available.
:param feature: The feature to check for.
:returns: ``True`` if available, ``False`` if unavailable, ``None`` if unknown.
:raises ValueError: If the feature is not defined in this version of Pillow.
"""
if feature not in feat... | [
"def",
"check_feature",
"(",
"feature",
")",
":",
"if",
"feature",
"not",
"in",
"features",
":",
"raise",
"ValueError",
"(",
"\"Unknown feature %s\"",
"%",
"feature",
")",
"module",
",",
"flag",
",",
"ver",
"=",
"features",
"[",
"feature",
"]",
"try",
":",... | [
126,
0
] | [
143,
19
] | python | en | ['en', 'error', 'th'] | False |
version_feature | (feature) |
:param feature: The feature to check for.
:returns: The version number as a string, or ``None`` if not available.
:raises ValueError: If the feature is not defined in this version of Pillow.
|
:param feature: The feature to check for.
:returns: The version number as a string, or ``None`` if not available.
:raises ValueError: If the feature is not defined in this version of Pillow.
| def version_feature(feature):
"""
:param feature: The feature to check for.
:returns: The version number as a string, or ``None`` if not available.
:raises ValueError: If the feature is not defined in this version of Pillow.
"""
if not check_feature(feature):
return None
module, fla... | [
"def",
"version_feature",
"(",
"feature",
")",
":",
"if",
"not",
"check_feature",
"(",
"feature",
")",
":",
"return",
"None",
"module",
",",
"flag",
",",
"ver",
"=",
"features",
"[",
"feature",
"]",
"if",
"ver",
"is",
"None",
":",
"return",
"None",
"re... | [
146,
0
] | [
160,
59
] | python | en | ['en', 'error', 'th'] | False |
get_supported_features | () |
:returns: A list of all supported features.
|
:returns: A list of all supported features.
| def get_supported_features():
"""
:returns: A list of all supported features.
"""
return [f for f in features if check_feature(f)] | [
"def",
"get_supported_features",
"(",
")",
":",
"return",
"[",
"f",
"for",
"f",
"in",
"features",
"if",
"check_feature",
"(",
"f",
")",
"]"
] | [
163,
0
] | [
167,
52
] | python | en | ['en', 'error', 'th'] | False |
check | (feature) |
:param feature: A module, codec, or feature name.
:returns:
``True`` if the module, codec, or feature is available,
``False`` or ``None`` otherwise.
|
:param feature: A module, codec, or feature name.
:returns:
``True`` if the module, codec, or feature is available,
``False`` or ``None`` otherwise.
| def check(feature):
"""
:param feature: A module, codec, or feature name.
:returns:
``True`` if the module, codec, or feature is available,
``False`` or ``None`` otherwise.
"""
if feature in modules:
return check_module(feature)
if feature in codecs:
return check... | [
"def",
"check",
"(",
"feature",
")",
":",
"if",
"feature",
"in",
"modules",
":",
"return",
"check_module",
"(",
"feature",
")",
"if",
"feature",
"in",
"codecs",
":",
"return",
"check_codec",
"(",
"feature",
")",
"if",
"feature",
"in",
"features",
":",
"r... | [
170,
0
] | [
185,
16
] | python | en | ['en', 'error', 'th'] | False |
version | (feature) |
:param feature:
The module, codec, or feature to check for.
:returns:
The version number as a string, or ``None`` if unknown or not available.
|
:param feature:
The module, codec, or feature to check for.
:returns:
The version number as a string, or ``None`` if unknown or not available.
| def version(feature):
"""
:param feature:
The module, codec, or feature to check for.
:returns:
The version number as a string, or ``None`` if unknown or not available.
"""
if feature in modules:
return version_module(feature)
if feature in codecs:
return version_... | [
"def",
"version",
"(",
"feature",
")",
":",
"if",
"feature",
"in",
"modules",
":",
"return",
"version_module",
"(",
"feature",
")",
"if",
"feature",
"in",
"codecs",
":",
"return",
"version_codec",
"(",
"feature",
")",
"if",
"feature",
"in",
"features",
":"... | [
188,
0
] | [
201,
15
] | python | en | ['en', 'error', 'th'] | False |
get_supported | () |
:returns: A list of all supported modules, features, and codecs.
|
:returns: A list of all supported modules, features, and codecs.
| def get_supported():
"""
:returns: A list of all supported modules, features, and codecs.
"""
ret = get_supported_modules()
ret.extend(get_supported_features())
ret.extend(get_supported_codecs())
return ret | [
"def",
"get_supported",
"(",
")",
":",
"ret",
"=",
"get_supported_modules",
"(",
")",
"ret",
".",
"extend",
"(",
"get_supported_features",
"(",
")",
")",
"ret",
".",
"extend",
"(",
"get_supported_codecs",
"(",
")",
")",
"return",
"ret"
] | [
204,
0
] | [
212,
14
] | python | en | ['en', 'error', 'th'] | False |
pilinfo | (out=None, supported_formats=True) |
Prints information about this installation of Pillow.
This function can be called with ``python -m PIL``.
:param out:
The output stream to print to. Defaults to ``sys.stdout`` if ``None``.
:param supported_formats:
If ``True``, a list of all supported image file formats will be printed... |
Prints information about this installation of Pillow.
This function can be called with ``python -m PIL``. | def pilinfo(out=None, supported_formats=True):
"""
Prints information about this installation of Pillow.
This function can be called with ``python -m PIL``.
:param out:
The output stream to print to. Defaults to ``sys.stdout`` if ``None``.
:param supported_formats:
If ``True``, a li... | [
"def",
"pilinfo",
"(",
"out",
"=",
"None",
",",
"supported_formats",
"=",
"True",
")",
":",
"if",
"out",
"is",
"None",
":",
"out",
"=",
"sys",
".",
"stdout",
"Image",
".",
"init",
"(",
")",
"print",
"(",
"\"-\"",
"*",
"68",
",",
"file",
"=",
"out... | [
215,
0
] | [
308,
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.