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
DatabaseIntrospection.get_table_list
(self, cursor)
Return a list of table and view names in the current database.
Return a list of table and view names in the current database.
def get_table_list(self, cursor): """Return a list of table and view names in the current database.""" cursor.execute("SHOW FULL TABLES") return [TableInfo(row[0], {'BASE TABLE': 't', 'VIEW': 'v'}.get(row[1])) for row in cursor.fetchall()]
[ "def", "get_table_list", "(", "self", ",", "cursor", ")", ":", "cursor", ".", "execute", "(", "\"SHOW FULL TABLES\"", ")", "return", "[", "TableInfo", "(", "row", "[", "0", "]", ",", "{", "'BASE TABLE'", ":", "'t'", ",", "'VIEW'", ":", "'v'", "}", ".",...
[ 66, 4 ]
[ 70, 45 ]
python
en
['en', 'en', 'en']
True
DatabaseIntrospection.get_table_description
(self, cursor, table_name)
Return a description of the table with the DB-API cursor.description interface."
Return a description of the table with the DB-API cursor.description interface."
def get_table_description(self, cursor, table_name): """ Return a description of the table with the DB-API cursor.description interface." """ json_constraints = {} if self.connection.mysql_is_mariadb and self.connection.features.can_introspect_json_field: # JS...
[ "def", "get_table_description", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "json_constraints", "=", "{", "}", "if", "self", ".", "connection", ".", "mysql_is_mariadb", "and", "self", ".", "connection", ".", "features", ".", "can_introspect_json_fie...
[ 72, 4 ]
[ 141, 21 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_relations
(self, cursor, table_name)
Return a dictionary of {field_name: (field_name_other_table, other_table)} representing all relationships to the given table.
Return a dictionary of {field_name: (field_name_other_table, other_table)} representing all relationships to the given table.
def get_relations(self, cursor, table_name): """ Return a dictionary of {field_name: (field_name_other_table, other_table)} representing all relationships to the given table. """ constraints = self.get_key_columns(cursor, table_name) relations = {} for my_fieldnam...
[ "def", "get_relations", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "constraints", "=", "self", ".", "get_key_columns", "(", "cursor", ",", "table_name", ")", "relations", "=", "{", "}", "for", "my_fieldname", ",", "other_table", ",", "other_fie...
[ 150, 4 ]
[ 159, 24 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_key_columns
(self, cursor, table_name)
Return a list of (column_name, referenced_table_name, referenced_column_name) for all key columns in the given table.
Return a list of (column_name, referenced_table_name, referenced_column_name) for all key columns in the given table.
def get_key_columns(self, cursor, table_name): """ Return a list of (column_name, referenced_table_name, referenced_column_name) for all key columns in the given table. """ key_columns = [] cursor.execute(""" SELECT column_name, referenced_table_name, referenc...
[ "def", "get_key_columns", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "key_columns", "=", "[", "]", "cursor", ".", "execute", "(", "\"\"\"\n SELECT column_name, referenced_table_name, referenced_column_name\n FROM information_schema.key_column_u...
[ 161, 4 ]
[ 175, 26 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_storage_engine
(self, cursor, table_name)
Retrieve the storage engine for a given table. Return the default storage engine if the table doesn't exist.
Retrieve the storage engine for a given table. Return the default storage engine if the table doesn't exist.
def get_storage_engine(self, cursor, table_name): """ Retrieve the storage engine for a given table. Return the default storage engine if the table doesn't exist. """ cursor.execute( "SELECT engine " "FROM information_schema.tables " "WHERE tab...
[ "def", "get_storage_engine", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "cursor", ".", "execute", "(", "\"SELECT engine \"", "\"FROM information_schema.tables \"", "\"WHERE table_name = %s\"", ",", "[", "table_name", "]", ")", "result", "=", "cursor", ...
[ 177, 4 ]
[ 189, 24 ]
python
en
['en', 'error', 'th']
False
DatabaseIntrospection.get_constraints
(self, cursor, table_name)
Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns.
Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns.
def get_constraints(self, cursor, table_name): """ Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns. """ constraints = {} # Get the actual constraint names and columns name_query = """ SELECT kc.`constraint_nam...
[ "def", "get_constraints", "(", "self", ",", "cursor", ",", "table_name", ")", ":", "constraints", "=", "{", "}", "# Get the actual constraint names and columns", "name_query", "=", "\"\"\"\n SELECT kc.`constraint_name`, kc.`column_name`,\n kc.`referenced_t...
[ 204, 4 ]
[ 314, 26 ]
python
en
['en', 'error', 'th']
False
reconstruction_evaluation
(X_time_orig, X_time_recon, training_mode)
Reconstruction loss on evaluation set. Given time major original and reconstructed features data and the training mode, return loss and eval_metrics_ops. Args: X_time_orig: Time major original features data. X_time_recon: Time major reconstructed features data. training_mode: Current training mode. ...
Reconstruction loss on evaluation set.
def reconstruction_evaluation(X_time_orig, X_time_recon, training_mode): """Reconstruction loss on evaluation set. Given time major original and reconstructed features data and the training mode, return loss and eval_metrics_ops. Args: X_time_orig: Time major original features data. X_time_recon: Time...
[ "def", "reconstruction_evaluation", "(", "X_time_orig", ",", "X_time_recon", ",", "training_mode", ")", ":", "loss", "=", "tf", ".", "losses", ".", "mean_squared_error", "(", "labels", "=", "X_time_orig", ",", "predictions", "=", "X_time_recon", ")", "eval_metric_...
[ 3, 0 ]
[ 32, 30 ]
python
en
['en', 'en', 'en']
True
RandomRec.__init__
(self, train_file=None, test_file=None, output_file=None, rank_length=10, sep='\t', output_sep='\t')
Random Recommender for Item Recommendation This algorithm predicts a rank for each user using the count of number of feedback of users and items Usage:: >> RandomRec(train).compute() >> RandomRec(train, test, ranking).compute() :param train_file: File which c...
Random Recommender for Item Recommendation
def __init__(self, train_file=None, test_file=None, output_file=None, rank_length=10, sep='\t', output_sep='\t'): """ Random Recommender for Item Recommendation This algorithm predicts a rank for each user using the count of number of feedback of users and items Usage:: >>...
[ "def", "__init__", "(", "self", ",", "train_file", "=", "None", ",", "test_file", "=", "None", ",", "output_file", "=", "None", ",", "rank_length", "=", "10", ",", "sep", "=", "'\\t'", ",", "output_sep", "=", "'\\t'", ")", ":", "super", "(", "RandomRec...
[ 20, 4 ]
[ 56, 52 ]
python
en
['en', 'error', 'th']
False
RandomRec.predict
(self)
Method to predict a rank for each user. For each pair out of train set, predict a random score for it.
Method to predict a rank for each user.
def predict(self): """ Method to predict a rank for each user. For each pair out of train set, predict a random score for it. """ for user in set(self.users): predictions = list() for item in self.train_set['items_unobserved'].get(user, []): ...
[ "def", "predict", "(", "self", ")", ":", "for", "user", "in", "set", "(", "self", ".", "users", ")", ":", "predictions", "=", "list", "(", ")", "for", "item", "in", "self", ".", "train_set", "[", "'items_unobserved'", "]", ".", "get", "(", "user", ...
[ 58, 4 ]
[ 71, 58 ]
python
en
['en', 'error', 'th']
False
RandomRec.compute
(self, verbose=True, metrics=None, verbose_evaluation=True, as_table=False, table_sep='\t')
Extends compute method from BaseItemRecommendation. Method to run recommender algorithm :param verbose: Print recommender and database information :type verbose: bool, default True :param metrics: List of evaluation metrics :type metrics: list, default None :param ver...
Extends compute method from BaseItemRecommendation. Method to run recommender algorithm
def compute(self, verbose=True, metrics=None, verbose_evaluation=True, as_table=False, table_sep='\t'): """ Extends compute method from BaseItemRecommendation. Method to run recommender algorithm :param verbose: Print recommender and database information :type verbose: bool, default Tru...
[ "def", "compute", "(", "self", ",", "verbose", "=", "True", ",", "metrics", "=", "None", ",", "verbose_evaluation", "=", "True", ",", "as_table", "=", "False", ",", "table_sep", "=", "'\\t'", ")", ":", "super", "(", "RandomRec", ",", "self", ")", ".", ...
[ 73, 4 ]
[ 106, 94 ]
python
en
['en', 'error', 'th']
False
tune_anomaly_thresholds_unsupervised_training
( cur_batch_size, time_anom_thresh_var, mahalanobis_dist_time, count_thresh_time_var, mean_thresh_time_var, var_thresh_time_var, feat_anom_thresh_var, mahalanobis_dist_feat, count_thresh_feat_var, mean_thresh_feat_var, var_thresh_feat_var, params, dummy_var)
Tunes anomaly thresholds during unsupervised training mode. Given dimensions of inputs, mahalanobis distances, and variables tracking counts, means, and variances of mahalanobis distance, returns loss and train_op. Args: cur_batch_size: Current batch size, could be partially filled. time_anom_thresh_v...
Tunes anomaly thresholds during unsupervised training mode.
def tune_anomaly_thresholds_unsupervised_training( cur_batch_size, time_anom_thresh_var, mahalanobis_dist_time, count_thresh_time_var, mean_thresh_time_var, var_thresh_time_var, feat_anom_thresh_var, mahalanobis_dist_feat, count_thresh_feat_var, mean_thresh_feat_var, var_thre...
[ "def", "tune_anomaly_thresholds_unsupervised_training", "(", "cur_batch_size", ",", "time_anom_thresh_var", ",", "mahalanobis_dist_time", ",", "count_thresh_time_var", ",", "mean_thresh_time_var", ",", "var_thresh_time_var", ",", "feat_anom_thresh_var", ",", "mahalanobis_dist_feat"...
[ 7, 0 ]
[ 125, 23 ]
python
en
['en', 'zu', 'en']
True
tune_anomaly_thresholds_unsupervised_eval
( cur_batch_size, time_anom_thresh_var, mahalanobis_dist_time, feat_anom_thresh_var, mahalanobis_dist_feat)
Checks tuned anomaly thresholds during supervised evaluation mode. Given dimensions of inputs, mahalanobis distances, and variables tracking counts, means, and variances of mahalanobis distance, returns loss and train_op. Args: cur_batch_size: Current batch size, could be partially filled. time_anom_t...
Checks tuned anomaly thresholds during supervised evaluation mode.
def tune_anomaly_thresholds_unsupervised_eval( cur_batch_size, time_anom_thresh_var, mahalanobis_dist_time, feat_anom_thresh_var, mahalanobis_dist_feat): """Checks tuned anomaly thresholds during supervised evaluation mode. Given dimensions of inputs, mahalanobis distances, and variables tracki...
[ "def", "tune_anomaly_thresholds_unsupervised_eval", "(", "cur_batch_size", ",", "time_anom_thresh_var", ",", "mahalanobis_dist_time", ",", "feat_anom_thresh_var", ",", "mahalanobis_dist_feat", ")", ":", "loss", "=", "tf", ".", "zeros", "(", "shape", "=", "[", "]", ","...
[ 128, 0 ]
[ 171, 30 ]
python
en
['en', 'en', 'en']
True
BaseManager.__str__
(self)
Return "app_label.model_label.manager_name".
Return "app_label.model_label.manager_name".
def __str__(self): """Return "app_label.model_label.manager_name".""" return '%s.%s' % (self.model._meta.label, self.name)
[ "def", "__str__", "(", "self", ")", ":", "return", "'%s.%s'", "%", "(", "self", ".", "model", ".", "_meta", ".", "label", ",", "self", ".", "name", ")" ]
[ 33, 4 ]
[ 35, 60 ]
python
en
['en', 'da', 'en']
False
BaseManager.deconstruct
(self)
Return a 5-tuple of the form (as_manager (True), manager_class, queryset_class, args, kwargs). Raise a ValueError if the manager is dynamically generated.
Return a 5-tuple of the form (as_manager (True), manager_class, queryset_class, args, kwargs).
def deconstruct(self): """ Return a 5-tuple of the form (as_manager (True), manager_class, queryset_class, args, kwargs). Raise a ValueError if the manager is dynamically generated. """ qs_class = self._queryset_class if getattr(self, '_built_with_as_manager', Fa...
[ "def", "deconstruct", "(", "self", ")", ":", "qs_class", "=", "self", ".", "_queryset_class", "if", "getattr", "(", "self", ",", "'_built_with_as_manager'", ",", "False", ")", ":", "# using MyQuerySet.as_manager()", "return", "(", "True", ",", "# as_manager", "N...
[ 40, 4 ]
[ 75, 13 ]
python
en
['en', 'error', 'th']
False
BaseManager._set_creation_counter
(self)
Set the creation counter value for this instance and increment the class-level copy.
Set the creation counter value for this instance and increment the class-level copy.
def _set_creation_counter(self): """ Set the creation counter value for this instance and increment the class-level copy. """ self.creation_counter = BaseManager.creation_counter BaseManager.creation_counter += 1
[ "def", "_set_creation_counter", "(", "self", ")", ":", "self", ".", "creation_counter", "=", "BaseManager", ".", "creation_counter", "BaseManager", ".", "creation_counter", "+=", "1" ]
[ 119, 4 ]
[ 125, 41 ]
python
en
['en', 'error', 'th']
False
BaseManager.get_queryset
(self)
Return a new QuerySet object. Subclasses can override this method to customize the behavior of the Manager.
Return a new QuerySet object. Subclasses can override this method to customize the behavior of the Manager.
def get_queryset(self): """ Return a new QuerySet object. Subclasses can override this method to customize the behavior of the Manager. """ return self._queryset_class(model=self.model, using=self._db, hints=self._hints)
[ "def", "get_queryset", "(", "self", ")", ":", "return", "self", ".", "_queryset_class", "(", "model", "=", "self", ".", "model", ",", "using", "=", "self", ".", "_db", ",", "hints", "=", "self", ".", "_hints", ")" ]
[ 141, 4 ]
[ 146, 88 ]
python
en
['en', 'error', 'th']
False
task_log_audit
(self: Task, user_id: int, verb: AuditVerbEnum, app_label: str, model: str, object_id: int)
log changes into audit
log changes into audit
def task_log_audit(self: Task, user_id: int, verb: AuditVerbEnum, app_label: str, model: str, object_id: int): """ log changes into audit """ try: # get object using content type obj_type = ContentType.objects.get(app_label=app_label, model=model) user = User.objects.get(id=user_id) ...
[ "def", "task_log_audit", "(", "self", ":", "Task", ",", "user_id", ":", "int", ",", "verb", ":", "AuditVerbEnum", ",", "app_label", ":", "str", ",", "model", ":", "str", ",", "object_id", ":", "int", ")", ":", "try", ":", "# get object using content type",...
[ 13, 0 ]
[ 26, 42 ]
python
en
['en', 'da', 'en']
True
optimize
(node, environment)
The context hint can be used to perform an static optimization based on the context given.
The context hint can be used to perform an static optimization based on the context given.
def optimize(node, environment): """The context hint can be used to perform an static optimization based on the context given.""" optimizer = Optimizer(environment) return optimizer.visit(node)
[ "def", "optimize", "(", "node", ",", "environment", ")", ":", "optimizer", "=", "Optimizer", "(", "environment", ")", "return", "optimizer", ".", "visit", "(", "node", ")" ]
[ 22, 0 ]
[ 26, 32 ]
python
en
['en', 'en', 'en']
True
Optimizer.fold
(self, node, eval_ctx=None)
Do constant folding.
Do constant folding.
def fold(self, node, eval_ctx=None): """Do constant folding.""" node = self.generic_visit(node) try: return nodes.Const.from_untrusted(node.as_const(eval_ctx), lineno=node.lineno, environment=...
[ "def", "fold", "(", "self", ",", "node", ",", "eval_ctx", "=", "None", ")", ":", "node", "=", "self", ".", "generic_visit", "(", "node", ")", "try", ":", "return", "nodes", ".", "Const", ".", "from_untrusted", "(", "node", ".", "as_const", "(", "eval...
[ 34, 4 ]
[ 42, 23 ]
python
en
['en', 'pt', 'en']
True
MultipleObjectMixin.get_queryset
(self)
Return the list of items for this view. The return value must be an iterable and may be an instance of `QuerySet` in which case `QuerySet` specific behavior will be enabled.
Return the list of items for this view.
def get_queryset(self): """ Return the list of items for this view. The return value must be an iterable and may be an instance of `QuerySet` in which case `QuerySet` specific behavior will be enabled. """ if self.queryset is not None: queryset = self.queryse...
[ "def", "get_queryset", "(", "self", ")", ":", "if", "self", ".", "queryset", "is", "not", "None", ":", "queryset", "=", "self", ".", "queryset", "if", "isinstance", "(", "queryset", ",", "QuerySet", ")", ":", "queryset", "=", "queryset", ".", "all", "(...
[ 20, 4 ]
[ 47, 23 ]
python
en
['en', 'error', 'th']
False
MultipleObjectMixin.get_ordering
(self)
Return the field or fields to use for ordering the queryset.
Return the field or fields to use for ordering the queryset.
def get_ordering(self): """Return the field or fields to use for ordering the queryset.""" return self.ordering
[ "def", "get_ordering", "(", "self", ")", ":", "return", "self", ".", "ordering" ]
[ 49, 4 ]
[ 51, 28 ]
python
en
['en', 'en', 'en']
True
MultipleObjectMixin.paginate_queryset
(self, queryset, page_size)
Paginate the queryset, if needed.
Paginate the queryset, if needed.
def paginate_queryset(self, queryset, page_size): """Paginate the queryset, if needed.""" paginator = self.get_paginator( queryset, page_size, orphans=self.get_paginate_orphans(), allow_empty_first_page=self.get_allow_empty()) page_kwarg = self.page_kwarg page = s...
[ "def", "paginate_queryset", "(", "self", ",", "queryset", ",", "page_size", ")", ":", "paginator", "=", "self", ".", "get_paginator", "(", "queryset", ",", "page_size", ",", "orphans", "=", "self", ".", "get_paginate_orphans", "(", ")", ",", "allow_empty_first...
[ 53, 4 ]
[ 74, 14 ]
python
en
['en', 'en', 'en']
True
MultipleObjectMixin.get_paginate_by
(self, queryset)
Get the number of items to paginate by, or ``None`` for no pagination.
Get the number of items to paginate by, or ``None`` for no pagination.
def get_paginate_by(self, queryset): """ Get the number of items to paginate by, or ``None`` for no pagination. """ return self.paginate_by
[ "def", "get_paginate_by", "(", "self", ",", "queryset", ")", ":", "return", "self", ".", "paginate_by" ]
[ 76, 4 ]
[ 80, 31 ]
python
en
['en', 'error', 'th']
False
MultipleObjectMixin.get_paginator
(self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)
Return an instance of the paginator for this view.
Return an instance of the paginator for this view.
def get_paginator(self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs): """Return an instance of the paginator for this view.""" return self.paginator_class( queryset, per_page, orphans=orphans, allow_empty_first_page=allow_empty_first...
[ "def", "get_paginator", "(", "self", ",", "queryset", ",", "per_page", ",", "orphans", "=", "0", ",", "allow_empty_first_page", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "paginator_class", "(", "queryset", ",", "per_page", ",",...
[ 82, 4 ]
[ 87, 68 ]
python
en
['en', 'en', 'en']
True
MultipleObjectMixin.get_paginate_orphans
(self)
Return the maximum number of orphans extend the last page by when paginating.
Return the maximum number of orphans extend the last page by when paginating.
def get_paginate_orphans(self): """ Return the maximum number of orphans extend the last page by when paginating. """ return self.paginate_orphans
[ "def", "get_paginate_orphans", "(", "self", ")", ":", "return", "self", ".", "paginate_orphans" ]
[ 89, 4 ]
[ 94, 36 ]
python
en
['en', 'error', 'th']
False
MultipleObjectMixin.get_allow_empty
(self)
Return ``True`` if the view should display empty lists and ``False`` if a 404 should be raised instead.
Return ``True`` if the view should display empty lists and ``False`` if a 404 should be raised instead.
def get_allow_empty(self): """ Return ``True`` if the view should display empty lists and ``False`` if a 404 should be raised instead. """ return self.allow_empty
[ "def", "get_allow_empty", "(", "self", ")", ":", "return", "self", ".", "allow_empty" ]
[ 96, 4 ]
[ 101, 31 ]
python
en
['en', 'error', 'th']
False
MultipleObjectMixin.get_context_object_name
(self, object_list)
Get the name of the item to be used in the context.
Get the name of the item to be used in the context.
def get_context_object_name(self, object_list): """Get the name of the item to be used in the context.""" if self.context_object_name: return self.context_object_name elif hasattr(object_list, 'model'): return '%s_list' % object_list.model._meta.model_name else: ...
[ "def", "get_context_object_name", "(", "self", ",", "object_list", ")", ":", "if", "self", ".", "context_object_name", ":", "return", "self", ".", "context_object_name", "elif", "hasattr", "(", "object_list", ",", "'model'", ")", ":", "return", "'%s_list'", "%",...
[ 103, 4 ]
[ 110, 23 ]
python
en
['en', 'en', 'en']
True
MultipleObjectMixin.get_context_data
(self, *, object_list=None, **kwargs)
Get the context for this view.
Get the context for this view.
def get_context_data(self, *, object_list=None, **kwargs): """Get the context for this view.""" queryset = object_list if object_list is not None else self.object_list page_size = self.get_paginate_by(queryset) context_object_name = self.get_context_object_name(queryset) if page_...
[ "def", "get_context_data", "(", "self", ",", "*", ",", "object_list", "=", "None", ",", "*", "*", "kwargs", ")", ":", "queryset", "=", "object_list", "if", "object_list", "is", "not", "None", "else", "self", ".", "object_list", "page_size", "=", "self", ...
[ 112, 4 ]
[ 135, 50 ]
python
en
['en', 'en', 'en']
True
MultipleObjectTemplateResponseMixin.get_template_names
(self)
Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.
Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.
def get_template_names(self): """ Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden. """ try: names = super().get_template_names() except ImproperlyConfigured: # If...
[ "def", "get_template_names", "(", "self", ")", ":", "try", ":", "names", "=", "super", "(", ")", ".", "get_template_names", "(", ")", "except", "ImproperlyConfigured", ":", "# If template_name isn't specified, it's not a problem --", "# we just start with an empty list.", ...
[ 164, 4 ]
[ 190, 20 ]
python
en
['en', 'error', 'th']
False
image_resize2square
(image, desired_size=None)
Resize image to a square by specific resolution(desired_size).
Resize image to a square by specific resolution(desired_size).
def image_resize2square(image, desired_size=None): ''' Resize image to a square by specific resolution(desired_size). ''' assert (image is not None), 'Image cannot be None.' # Initialize the dimensions of the image to be resized and # grab the size of image old_size = image.shape[:2] #...
[ "def", "image_resize2square", "(", "image", ",", "desired_size", "=", "None", ")", ":", "assert", "(", "image", "is", "not", "None", ")", ",", "'Image cannot be None.'", "# Initialize the dimensions of the image to be resized and", "# grab the size of image", "old_size", ...
[ 49, 0 ]
[ 82, 20 ]
python
en
['en', 'error', 'th']
False
create_path
(data_dir)
Create a specific path to store result images. - Under the data directory, two separated folders will store image and masking files - Example: - data_dir- |- IMAGE_FOLDER |- MASK_FOLDER
Create a specific path to store result images. - Under the data directory, two separated folders will store image and masking files - Example: - data_dir- |- IMAGE_FOLDER |- MASK_FOLDER
def create_path(data_dir): ''' Create a specific path to store result images. - Under the data directory, two separated folders will store image and masking files - Example: - data_dir- |- IMAGE_FOLDER |- MASK_FOLDER ''' try: output_image_path = join(data...
[ "def", "create_path", "(", "data_dir", ")", ":", "try", ":", "output_image_path", "=", "join", "(", "data_dir", ",", "IMAGE_FOLDER", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "output_image_path", ")", ":", "os", ".", "makedirs", "(", "outpu...
[ 85, 0 ]
[ 105, 15 ]
python
en
['en', 'error', 'th']
False
main
(args)
The main entry point of the program - This program will download image from MS COCO 2017 (Microsoft Common Objects in Context) repo and generate annotation to the specific object classes.
The main entry point of the program - This program will download image from MS COCO 2017 (Microsoft Common Objects in Context) repo and generate annotation to the specific object classes.
def main(args): ''' The main entry point of the program - This program will download image from MS COCO 2017 (Microsoft Common Objects in Context) repo and generate annotation to the specific object classes. ''' plt.ioff() data_dir = args.data_root_dir category_list = list(args....
[ "def", "main", "(", "args", ")", ":", "plt", ".", "ioff", "(", ")", "data_dir", "=", "args", ".", "data_root_dir", "category_list", "=", "list", "(", "args", ".", "category", ")", "annFile", "=", "args", ".", "annotation_file", "num", "=", "args", ".",...
[ 108, 0 ]
[ 177, 15 ]
python
en
['en', 'error', 'th']
False
PostGISAdapter.__init__
(self, obj, geography=False)
Initialize on the spatial object.
Initialize on the spatial object.
def __init__(self, obj, geography=False): """ Initialize on the spatial object. """ self.is_geometry = isinstance(obj, (GEOSGeometry, PostGISAdapter)) # Getting the WKB (in string form, to allow easy pickling of # the adaptor) and the SRID from the geometry or raster. ...
[ "def", "__init__", "(", "self", ",", "obj", ",", "geography", "=", "False", ")", ":", "self", ".", "is_geometry", "=", "isinstance", "(", "obj", ",", "(", "GEOSGeometry", ",", "PostGISAdapter", ")", ")", "# Getting the WKB (in string form, to allow easy pickling o...
[ 11, 4 ]
[ 26, 34 ]
python
en
['en', 'error', 'th']
False
PostGISAdapter.__conform__
(self, proto)
Does the given protocol conform to what Psycopg2 expects?
Does the given protocol conform to what Psycopg2 expects?
def __conform__(self, proto): """Does the given protocol conform to what Psycopg2 expects?""" if proto == ISQLQuote: return self else: raise Exception('Error implementing psycopg2 protocol. Is psycopg2 installed?')
[ "def", "__conform__", "(", "self", ",", "proto", ")", ":", "if", "proto", "==", "ISQLQuote", ":", "return", "self", "else", ":", "raise", "Exception", "(", "'Error implementing psycopg2 protocol. Is psycopg2 installed?'", ")" ]
[ 28, 4 ]
[ 33, 91 ]
python
en
['en', 'en', 'en']
True
PostGISAdapter.prepare
(self, conn)
This method allows escaping the binary in the style required by the server's `standard_conforming_string` setting.
This method allows escaping the binary in the style required by the server's `standard_conforming_string` setting.
def prepare(self, conn): """ This method allows escaping the binary in the style required by the server's `standard_conforming_string` setting. """ if self.is_geometry: self._adapter.prepare(conn)
[ "def", "prepare", "(", "self", ",", "conn", ")", ":", "if", "self", ".", "is_geometry", ":", "self", ".", "_adapter", ".", "prepare", "(", "conn", ")" ]
[ 48, 4 ]
[ 54, 39 ]
python
en
['en', 'error', 'th']
False
PostGISAdapter.getquoted
(self)
Return a properly quoted string for use in PostgreSQL/PostGIS.
Return a properly quoted string for use in PostgreSQL/PostGIS.
def getquoted(self): """ Return a properly quoted string for use in PostgreSQL/PostGIS. """ if self.is_geometry: # Psycopg will figure out whether to use E'\\000' or '\000'. return '%s(%s)' % ( 'ST_GeogFromWKB' if self.geography else 'ST_GeomFromEW...
[ "def", "getquoted", "(", "self", ")", ":", "if", "self", ".", "is_geometry", ":", "# Psycopg will figure out whether to use E'\\\\000' or '\\000'.", "return", "'%s(%s)'", "%", "(", "'ST_GeogFromWKB'", "if", "self", ".", "geography", "else", "'ST_GeomFromEWKB'", ",", "...
[ 56, 4 ]
[ 68, 45 ]
python
en
['en', 'error', 'th']
False
upsample
(base_model, x, layers, mode: XModelMode)
Feature extraction upsampling/generation before regression and heatmap heads. :param base_model: tf.keras.Model object :param x: output from last layer of base_model :param layers: layer names from backbone :param mode: upsampling mode for features :return: base_model and features
Feature extraction upsampling/generation before regression and heatmap heads. :param base_model: tf.keras.Model object :param x: output from last layer of base_model :param layers: layer names from backbone :param mode: upsampling mode for features :return: base_model and features
def upsample(base_model, x, layers, mode: XModelMode): """ Feature extraction upsampling/generation before regression and heatmap heads. :param base_model: tf.keras.Model object :param x: output from last layer of base_model :param layers: layer names from backbone :param mode: upsampling mode ...
[ "def", "upsample", "(", "base_model", ",", "x", ",", "layers", ",", "mode", ":", "XModelMode", ")", ":", "with", "tf", ".", "name_scope", "(", "\"upsample\"", ")", ":", "layers", "=", "[", "base_model", ".", "get_layer", "(", "layer_name", ")", "for", ...
[ 13, 0 ]
[ 70, 53 ]
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
video_and_frame_level_model
(features, labels, mode, params)
features['video_id'].shape = (batch_size, 1) features['mean_rgb'].shape = (batch_size, 1024) features['mean_audio'].shape = (batch_size, 128) features['rgb'].shape = (batch_size, MAX_FRAMES, 1024) features['audio'].shape = (batch_size, MAX_FRAMES, 128)
features['video_id'].shape = (batch_size, 1) features['mean_rgb'].shape = (batch_size, 1024) features['mean_audio'].shape = (batch_size, 128) features['rgb'].shape = (batch_size, MAX_FRAMES, 1024) features['audio'].shape = (batch_size, MAX_FRAMES, 128)
def video_and_frame_level_model(features, labels, mode, params): ''' features['video_id'].shape = (batch_size, 1) features['mean_rgb'].shape = (batch_size, 1024) features['mean_audio'].shape = (batch_size, 128) features['rgb'].shape = (batch_size, MAX_FRAMES, 1024) features['audio'].shape = (batch_size, M...
[ "def", "video_and_frame_level_model", "(", "features", ",", "labels", ",", "mode", ",", "params", ")", ":", "print", "(", "\"\\nvideo_and_frame_level_model: features = {}\"", ".", "format", "(", "features", ")", ")", "print", "(", "\"video_and_frame_level_model: labels ...
[ 197, 0 ]
[ 350, 40 ]
python
en
['en', 'error', 'th']
False
FileSystemKeyValueStorage.__init__
(self, root_path)
Create a new Storage object. All files will be stored under the root_path location :param root_path: The base folder for all storage files
Create a new Storage object.
def __init__(self, root_path): """ Create a new Storage object. All files will be stored under the root_path location :param root_path: The base folder for all storage files """ if root_path is None: root_path = gettempdir() if not os.path.isdir(roo...
[ "def", "__init__", "(", "self", ",", "root_path", ")", ":", "if", "root_path", "is", "None", ":", "root_path", "=", "gettempdir", "(", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "root_path", ")", ":", "os", ".", "makedirs", "(", "root_pa...
[ 14, 4 ]
[ 28, 35 ]
python
en
['en', 'error', 'th']
False
FileSystemKeyValueStorage._get_key_full_path
(self, key)
Generate the file path for the key :param key: The key :return: The absolute path of the value file associated with the key
Generate the file path for the key
def _get_key_full_path(self, key): """ Generate the file path for the key :param key: The key :return: The absolute path of the value file associated with the key """ return os.path.join(self._root_path, key + self._item_ext)
[ "def", "_get_key_full_path", "(", "self", ",", "key", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "_root_path", ",", "key", "+", "self", ".", "_item_ext", ")" ]
[ 60, 4 ]
[ 68, 66 ]
python
en
['en', 'error', 'th']
False
FileSystemKeyValueStorage._exists
(self, key)
Indicate whether key exists :param key: The key :return: bool True if the file for the given key exists
Indicate whether key exists
def _exists(self, key): """ Indicate whether key exists :param key: The key :return: bool True if the file for the given key exists """ return os.path.isfile(self._get_key_full_path(key))
[ "def", "_exists", "(", "self", ",", "key", ")", ":", "return", "os", ".", "path", ".", "isfile", "(", "self", ".", "_get_key_full_path", "(", "key", ")", ")" ]
[ 70, 4 ]
[ 78, 59 ]
python
en
['en', 'error', 'th']
False
api_client
()
api client without authentication
api client without authentication
def api_client() -> Generator[APIClient, None, None]: """ api client without authentication """ from rest_framework.test import APIClient yield APIClient()
[ "def", "api_client", "(", ")", "->", "Generator", "[", "APIClient", ",", "None", ",", "None", "]", ":", "from", "rest_framework", ".", "test", "import", "APIClient", "yield", "APIClient", "(", ")" ]
[ 14, 0 ]
[ 17, 21 ]
python
en
['en', 'fr', 'en']
True
auth_api_client
(db, api_client)
APIClient with authentication factory
APIClient with authentication factory
def auth_api_client(db, api_client): """ APIClient with authentication factory """ def make_auth_client(user: AbstractUser) -> APIClient: # api_client.force_login(user=user) # login api_client.force_authenticate(user=user) return api_client yield make_auth_client # lo...
[ "def", "auth_api_client", "(", "db", ",", "api_client", ")", ":", "def", "make_auth_client", "(", "user", ":", "AbstractUser", ")", "->", "APIClient", ":", "# api_client.force_login(user=user)", "# login", "api_client", ".", "force_authenticate", "(", "user", "=", ...
[ 21, 0 ]
[ 34, 44 ]
python
en
['en', 'en', 'en']
True
create_user
(db, django_user_model: AbstractUser, test_password: str)
factory for creating users
factory for creating users
def create_user(db, django_user_model: AbstractUser, test_password: str): """ factory for creating users """ def make_user(username, email, first_name, last_name) -> AbstractUser: new_user: AbstractUser = User.objects.create(username=username, email=email, ...
[ "def", "create_user", "(", "db", ",", "django_user_model", ":", "AbstractUser", ",", "test_password", ":", "str", ")", ":", "def", "make_user", "(", "username", ",", "email", ",", "first_name", ",", "last_name", ")", "->", "AbstractUser", ":", "new_user", ":...
[ 43, 0 ]
[ 54, 19 ]
python
en
['en', 'en', 'en']
True
create_image
()
image file factory
image file factory
def create_image(): """ image file factory """ with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tf: image = Image.new("RGB", (100, 100), color="#ddd") image.save(tf, format="JPEG") tf.close() yield tf # clean up image.close()
[ "def", "create_image", "(", ")", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "\".jpg\"", ",", "delete", "=", "False", ")", "as", "tf", ":", "image", "=", "Image", ".", "new", "(", "\"RGB\"", ",", "(", "100", ",", "100", ")...
[ 66, 0 ]
[ 76, 17 ]
python
en
['en', 'en', 'en']
True
delete_selected
(modeladmin, request, queryset)
Default action which deletes the selected objects. This action first displays a confirmation page which shows all the deletable objects, or, if the user has no permission one of the related childs (foreignkeys), a "permission denied" message. Next, it deletes all selected objects and redirects ba...
Default action which deletes the selected objects.
def delete_selected(modeladmin, request, queryset): """ Default action which deletes the selected objects. This action first displays a confirmation page which shows all the deletable objects, or, if the user has no permission one of the related childs (foreignkeys), a "permission denied" message. ...
[ "def", "delete_selected", "(", "modeladmin", ",", "request", ",", "queryset", ")", ":", "opts", "=", "modeladmin", ".", "model", ".", "_meta", "app_label", "=", "opts", ".", "app_label", "# Populate deletable_objects, a data structure of all related objects that", "# wi...
[ 17, 0 ]
[ 79, 15 ]
python
en
['en', 'error', 'th']
False
GroupBasedRecommender.__init__
(self, train_files=None, test_file=None, output_file=None, similarity_metric="cosine", rank_length=10, k_groups=3, recommender='UserKNN', as_binary=False, sep='\t', output_sep='\t', max_int_kmedoids=1000, parser='', user_weights=False)
Group-Based for Item Recommendation This algorithm predicts a rank for each user using a co-clustering algorithm Usage:: >> GroupBasedRecommender([train_history], test).compute() >> GroupBasedRecommender([train_history, train_rating], test, as_binary=True).compute() ...
Group-Based for Item Recommendation
def __init__(self, train_files=None, test_file=None, output_file=None, similarity_metric="cosine", rank_length=10, k_groups=3, recommender='UserKNN', as_binary=False, sep='\t', output_sep='\t', max_int_kmedoids=1000, parser='', user_weights=False): """ Group-Based for I...
[ "def", "__init__", "(", "self", ",", "train_files", "=", "None", ",", "test_file", "=", "None", ",", "output_file", "=", "None", ",", "similarity_metric", "=", "\"cosine\"", ",", "rank_length", "=", "10", ",", "k_groups", "=", "3", ",", "recommender", "=",...
[ 31, 4 ]
[ 89, 36 ]
python
en
['en', 'error', 'th']
False
GroupBasedRecommender.read_files
(self)
Method to initialize recommender algorithm.
Method to initialize recommender algorithm.
def read_files(self): """ Method to initialize recommender algorithm. """ self.n_files = len(self.train_files) self.users = [] self.items = [] for train_file in self.train_files: train_set = ReadFile(train_file, sep=self.sep, as_binary=self.as_bina...
[ "def", "read_files", "(", "self", ")", ":", "self", ".", "n_files", "=", "len", "(", "self", ".", "train_files", ")", "self", ".", "users", "=", "[", "]", "self", ".", "items", "=", "[", "]", "for", "train_file", "in", "self", ".", "train_files", "...
[ 91, 4 ]
[ 122, 50 ]
python
en
['en', 'error', 'th']
False
GroupBasedRecommender.compute_distance
(self)
Method to compute a distance matrix from train set
Method to compute a distance matrix from train set
def compute_distance(self): """ Method to compute a distance matrix from train set """ # Calculate distance matrix distance_matrix = np.float32(squareform(pdist(self.matrix, self.similarity_metric))) # Remove NaNs distance_matrix[np.isnan(distance_matrix)] = 1.0...
[ "def", "compute_distance", "(", "self", ")", ":", "# Calculate distance matrix", "distance_matrix", "=", "np", ".", "float32", "(", "squareform", "(", "pdist", "(", "self", ".", "matrix", ",", "self", ".", "similarity_metric", ")", ")", ")", "# Remove NaNs", "...
[ 124, 4 ]
[ 135, 30 ]
python
en
['en', 'error', 'th']
False
SelectionPreferences.__init__
( self, allow_yanked: bool, allow_all_prereleases: bool = False, format_control: Optional[FormatControl] = None, prefer_binary: bool = False, ignore_requires_python: Optional[bool] = None, )
Create a SelectionPreferences object. :param allow_yanked: Whether files marked as yanked (in the sense of PEP 592) are permitted to be candidates for install. :param format_control: A FormatControl object or None. Used to control the selection of source packages / binary packag...
Create a SelectionPreferences object.
def __init__( self, allow_yanked: bool, allow_all_prereleases: bool = False, format_control: Optional[FormatControl] = None, prefer_binary: bool = False, ignore_requires_python: Optional[bool] = None, ) -> None: """Create a SelectionPreferences object. ...
[ "def", "__init__", "(", "self", ",", "allow_yanked", ":", "bool", ",", "allow_all_prereleases", ":", "bool", "=", "False", ",", "format_control", ":", "Optional", "[", "FormatControl", "]", "=", "None", ",", "prefer_binary", ":", "bool", "=", "False", ",", ...
[ 18, 4 ]
[ 45, 60 ]
python
en
['en', 'en', 'en']
True
ValidationError.__init__
(self, message, code=None, params=None)
The `message` argument can be a single error, a list of errors, or a dictionary that maps field names to lists of errors. What we define as an "error" can be either a simple string or an instance of ValidationError with its message attribute set, and what we define as list or di...
The `message` argument can be a single error, a list of errors, or a dictionary that maps field names to lists of errors. What we define as an "error" can be either a simple string or an instance of ValidationError with its message attribute set, and what we define as list or di...
def __init__(self, message, code=None, params=None): """ The `message` argument can be a single error, a list of errors, or a dictionary that maps field names to lists of errors. What we define as an "error" can be either a simple string or an instance of ValidationError with its...
[ "def", "__init__", "(", "self", ",", "message", ",", "code", "=", "None", ",", "params", "=", "None", ")", ":", "super", "(", ")", ".", "__init__", "(", "message", ",", "code", ",", "params", ")", "if", "isinstance", "(", "message", ",", "ValidationE...
[ 108, 4 ]
[ 149, 36 ]
python
en
['en', 'error', 'th']
False
convert_parquet_to_iceberg
(parquet_file: ParquetFile)
Given two Iceberg schema's returns a list of column_names for all id's in the file schema that are projected in the expected schema Parameters ---------- parquet_file : pyarrow.parquet.ParquetFile The Parquet File to use to extract the iceberg schema Returns ------- iceberg.ap...
Given two Iceberg schema's returns a list of column_names for all id's in the file schema that are projected in the expected schema
def convert_parquet_to_iceberg(parquet_file: ParquetFile) -> Schema: # noqa: ignore=C901 """ Given two Iceberg schema's returns a list of column_names for all id's in the file schema that are projected in the expected schema Parameters ---------- parquet_file : pyarrow.parquet.ParquetFile ...
[ "def", "convert_parquet_to_iceberg", "(", "parquet_file", ":", "ParquetFile", ")", "->", "Schema", ":", "# noqa: ignore=C901", "return", "arrow_to_iceberg", "(", "parquet_file", ".", "schema_arrow", ")" ]
[ 119, 0 ]
[ 134, 54 ]
python
en
['en', 'error', 'th']
False
arrow_to_iceberg
(arrow_schema: pa.Schema)
Use an arrow schema, which contains the field_id metadata, to create an equivalent iceberg Schema Parameters ---------- arrow_schema : pyarrow.Schema An Arrow schema with the parquet field_id metadata Returns ------- iceberg.api.Schema returns an equivalent iceberg Schema ...
Use an arrow schema, which contains the field_id metadata, to create an equivalent iceberg Schema
def arrow_to_iceberg(arrow_schema: pa.Schema) -> Schema: """ Use an arrow schema, which contains the field_id metadata, to create an equivalent iceberg Schema Parameters ---------- arrow_schema : pyarrow.Schema An Arrow schema with the parquet field_id metadata Returns ------- ...
[ "def", "arrow_to_iceberg", "(", "arrow_schema", ":", "pa", ".", "Schema", ")", "->", "Schema", ":", "return", "Schema", "(", "[", "get_field", "(", "col", ")", "for", "col", "in", "arrow_schema", "]", ")" ]
[ 137, 0 ]
[ 151, 59 ]
python
en
['en', 'error', 'th']
False
train_and_evaluate
(args)
Train and evaluate custom Estimator with three training modes. Given the dictionary of parameters, create custom Estimator and run up to three training modes then return Estimator object. Args: args: Dictionary of parameters. Returns: Estimator object.
Train and evaluate custom Estimator with three training modes.
def train_and_evaluate(args): """Train and evaluate custom Estimator with three training modes. Given the dictionary of parameters, create custom Estimator and run up to three training modes then return Estimator object. Args: args: Dictionary of parameters. Returns: Estimator object. """ # Cre...
[ "def", "train_and_evaluate", "(", "args", ")", ":", "# Create our custom estimator using our model function", "estimator", "=", "tf", ".", "estimator", ".", "Estimator", "(", "model_fn", "=", "anomaly_detection", ",", "model_dir", "=", "args", "[", "\"output_dir\"", "...
[ 10, 0 ]
[ 138, 8 ]
python
en
['en', 'en', 'en']
True
ImagePalette.getdata
(self)
Get palette contents in format suitable for the low-level ``im.putpalette`` primitive. .. warning:: This method is experimental.
Get palette contents in format suitable for the low-level ``im.putpalette`` primitive.
def getdata(self): """ Get palette contents in format suitable for the low-level ``im.putpalette`` primitive. .. warning:: This method is experimental. """ if self.rawmode: return self.rawmode, self.palette return self.mode, self.tobytes()
[ "def", "getdata", "(", "self", ")", ":", "if", "self", ".", "rawmode", ":", "return", "self", ".", "rawmode", ",", "self", ".", "palette", "return", "self", ".", "mode", ",", "self", ".", "tobytes", "(", ")" ]
[ 72, 4 ]
[ 81, 40 ]
python
en
['en', 'error', 'th']
False
ImagePalette.tobytes
(self)
Convert palette to bytes. .. warning:: This method is experimental.
Convert palette to bytes.
def tobytes(self): """Convert palette to bytes. .. warning:: This method is experimental. """ if self.rawmode: raise ValueError("palette contains raw palette data") if isinstance(self.palette, bytes): return self.palette arr = array.array("B", sel...
[ "def", "tobytes", "(", "self", ")", ":", "if", "self", ".", "rawmode", ":", "raise", "ValueError", "(", "\"palette contains raw palette data\"", ")", "if", "isinstance", "(", "self", ".", "palette", ",", "bytes", ")", ":", "return", "self", ".", "palette", ...
[ 83, 4 ]
[ 93, 28 ]
python
en
['en', 'en', 'en']
True
ImagePalette.getcolor
(self, color, image=None)
Given an rgb tuple, allocate palette entry. .. warning:: This method is experimental.
Given an rgb tuple, allocate palette entry.
def getcolor(self, color, image=None): """Given an rgb tuple, allocate palette entry. .. warning:: This method is experimental. """ if self.rawmode: raise ValueError("palette contains raw palette data") if isinstance(color, tuple): if self.mode == "RGB": ...
[ "def", "getcolor", "(", "self", ",", "color", ",", "image", "=", "None", ")", ":", "if", "self", ".", "rawmode", ":", "raise", "ValueError", "(", "\"palette contains raw palette data\"", ")", "if", "isinstance", "(", "color", ",", "tuple", ")", ":", "if", ...
[ 98, 4 ]
[ 148, 71 ]
python
en
['en', 'en', 'it']
True
ImagePalette.save
(self, fp)
Save palette to text file. .. warning:: This method is experimental.
Save palette to text file.
def save(self, fp): """Save palette to text file. .. warning:: This method is experimental. """ if self.rawmode: raise ValueError("palette contains raw palette data") if isinstance(fp, str): fp = open(fp, "w") fp.write("# Palette\n") fp.wr...
[ "def", "save", "(", "self", ",", "fp", ")", ":", "if", "self", ".", "rawmode", ":", "raise", "ValueError", "(", "\"palette contains raw palette data\"", ")", "if", "isinstance", "(", "fp", ",", "str", ")", ":", "fp", "=", "open", "(", "fp", ",", "\"w\"...
[ 150, 4 ]
[ 169, 18 ]
python
en
['en', 'en', 'en']
True
load_coco_classes
(coco)
Loads the class to label mapping (and inverse) for COCO.
Loads the class to label mapping (and inverse) for COCO.
def load_coco_classes(coco): """ Loads the class to label mapping (and inverse) for COCO. """ # load class names (name -> label) categories = coco.loadCats(coco.getCatIds()) categories.sort(key=lambda x: x["id"]) classes = {} coco_labels = {} coco_labels_inverse = {} for c in catego...
[ "def", "load_coco_classes", "(", "coco", ")", ":", "# load class names (name -> label)", "categories", "=", "coco", ".", "loadCats", "(", "coco", ".", "getCatIds", "(", ")", ")", "categories", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "\"...
[ 21, 0 ]
[ 36, 52 ]
python
en
['en', 'en', 'en']
True
_execfile
(filename, globals, locals=None)
Python 3 implementation of execfile.
Python 3 implementation of execfile.
def _execfile(filename, globals, locals=None): """ Python 3 implementation of execfile. """ mode = 'rb' with open(filename, mode) as stream: script = stream.read() if locals is None: locals = globals code = compile(script, filename, 'exec') exec(code, globals, locals)
[ "def", "_execfile", "(", "filename", ",", "globals", ",", "locals", "=", "None", ")", ":", "mode", "=", "'rb'", "with", "open", "(", "filename", ",", "mode", ")", "as", "stream", ":", "script", "=", "stream", ".", "read", "(", ")", "if", "locals", ...
[ 34, 0 ]
[ 44, 31 ]
python
en
['en', 'error', 'th']
False
override_temp
(replacement)
Monkey-patch tempfile.tempdir with replacement, ensuring it exists
Monkey-patch tempfile.tempdir with replacement, ensuring it exists
def override_temp(replacement): """ Monkey-patch tempfile.tempdir with replacement, ensuring it exists """ pkg_resources.py31compat.makedirs(replacement, exist_ok=True) saved = tempfile.tempdir tempfile.tempdir = replacement try: yield finally: tempfile.tempdir = saved
[ "def", "override_temp", "(", "replacement", ")", ":", "pkg_resources", ".", "py31compat", ".", "makedirs", "(", "replacement", ",", "exist_ok", "=", "True", ")", "saved", "=", "tempfile", ".", "tempdir", "tempfile", ".", "tempdir", "=", "replacement", "try", ...
[ 68, 0 ]
[ 81, 32 ]
python
en
['en', 'error', 'th']
False
save_modules
()
Context in which imported modules are saved. Translates exceptions internal to the context into the equivalent exception outside the context.
Context in which imported modules are saved.
def save_modules(): """ Context in which imported modules are saved. Translates exceptions internal to the context into the equivalent exception outside the context. """ saved = sys.modules.copy() with ExceptionSaver() as saved_exc: yield saved sys.modules.update(saved) # r...
[ "def", "save_modules", "(", ")", ":", "saved", "=", "sys", ".", "modules", ".", "copy", "(", ")", "with", "ExceptionSaver", "(", ")", "as", "saved_exc", ":", "yield", "saved", "sys", ".", "modules", ".", "update", "(", "saved", ")", "# remove any modules...
[ 144, 0 ]
[ 165, 22 ]
python
en
['en', 'error', 'th']
False
_needs_hiding
(mod_name)
>>> _needs_hiding('setuptools') True >>> _needs_hiding('pkg_resources') True >>> _needs_hiding('setuptools_plugin') False >>> _needs_hiding('setuptools.__init__') True >>> _needs_hiding('distutils') True >>> _needs_hiding('os') False >>> _needs_hiding('Cython') T...
>>> _needs_hiding('setuptools') True >>> _needs_hiding('pkg_resources') True >>> _needs_hiding('setuptools_plugin') False >>> _needs_hiding('setuptools.__init__') True >>> _needs_hiding('distutils') True >>> _needs_hiding('os') False >>> _needs_hiding('Cython') T...
def _needs_hiding(mod_name): """ >>> _needs_hiding('setuptools') True >>> _needs_hiding('pkg_resources') True >>> _needs_hiding('setuptools_plugin') False >>> _needs_hiding('setuptools.__init__') True >>> _needs_hiding('distutils') True >>> _needs_hiding('os') False ...
[ "def", "_needs_hiding", "(", "mod_name", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r'(setuptools|pkg_resources|distutils|Cython)(\\.|$)'", ")", "return", "bool", "(", "pattern", ".", "match", "(", "mod_name", ")", ")" ]
[ 197, 0 ]
[ 215, 40 ]
python
en
['en', 'error', 'th']
False
hide_setuptools
()
Remove references to setuptools' modules from sys.modules to allow the invocation to import the most appropriate setuptools. This technique is necessary to avoid issues such as #315 where setuptools upgrading itself would fail to find a function declared in the metadata.
Remove references to setuptools' modules from sys.modules to allow the invocation to import the most appropriate setuptools. This technique is necessary to avoid issues such as #315 where setuptools upgrading itself would fail to find a function declared in the metadata.
def hide_setuptools(): """ Remove references to setuptools' modules from sys.modules to allow the invocation to import the most appropriate setuptools. This technique is necessary to avoid issues such as #315 where setuptools upgrading itself would fail to find a function declared in the metadata. ...
[ "def", "hide_setuptools", "(", ")", ":", "modules", "=", "filter", "(", "_needs_hiding", ",", "sys", ".", "modules", ")", "_clear_modules", "(", "modules", ")" ]
[ 218, 0 ]
[ 226, 27 ]
python
en
['en', 'error', 'th']
False
run_setup
(setup_script, args)
Run a distutils setup script, sandboxed in its directory
Run a distutils setup script, sandboxed in its directory
def run_setup(setup_script, args): """Run a distutils setup script, sandboxed in its directory""" setup_dir = os.path.abspath(os.path.dirname(setup_script)) with setup_context(setup_dir): try: sys.argv[:] = [setup_script] + list(args) sys.path.insert(0, setup_dir) ...
[ "def", "run_setup", "(", "setup_script", ",", "args", ")", ":", "setup_dir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "setup_script", ")", ")", "with", "setup_context", "(", "setup_dir", ")", ":", "try", ":",...
[ 229, 0 ]
[ 252, 21 ]
python
en
['en', 'lb', 'en']
True
UnpickleableException.dump
(type, exc)
Always return a dumped (pickled) type and exc. If exc can't be pickled, wrap it in UnpickleableException first.
Always return a dumped (pickled) type and exc. If exc can't be pickled, wrap it in UnpickleableException first.
def dump(type, exc): """ Always return a dumped (pickled) type and exc. If exc can't be pickled, wrap it in UnpickleableException first. """ try: return pickle.dumps(type), pickle.dumps(exc) except Exception: # get UnpickleableException inside the ...
[ "def", "dump", "(", "type", ",", "exc", ")", ":", "try", ":", "return", "pickle", ".", "dumps", "(", "type", ")", ",", "pickle", ".", "dumps", "(", "exc", ")", "except", "Exception", ":", "# get UnpickleableException inside the sandbox", "from", "setuptools"...
[ 100, 4 ]
[ 110, 48 ]
python
en
['en', 'error', 'th']
False
ExceptionSaver.resume
(self)
restore and re-raise any exception
restore and re-raise any exception
def resume(self): "restore and re-raise any exception" if '_saved' not in vars(self): return type, exc = map(pickle.loads, self._saved) six.reraise(type, exc, self._tb)
[ "def", "resume", "(", "self", ")", ":", "if", "'_saved'", "not", "in", "vars", "(", "self", ")", ":", "return", "type", ",", "exc", "=", "map", "(", "pickle", ".", "loads", ",", "self", ".", "_saved", ")", "six", ".", "reraise", "(", "type", ",",...
[ 133, 4 ]
[ 140, 40 ]
python
en
['en', 'en', 'en']
True
AbstractSandbox.run
(self, func)
Run 'func' under os sandboxing
Run 'func' under os sandboxing
def run(self, func): """Run 'func' under os sandboxing""" with self: return func()
[ "def", "run", "(", "self", ",", "func", ")", ":", "with", "self", ":", "return", "func", "(", ")" ]
[ 285, 4 ]
[ 288, 25 ]
python
es
['es', 'jv', 'pt']
False
AbstractSandbox._validate_path
(self, path)
Called to remap or validate any path, whether input or output
Called to remap or validate any path, whether input or output
def _validate_path(self, path): """Called to remap or validate any path, whether input or output""" return path
[ "def", "_validate_path", "(", "self", ",", "path", ")", ":", "return", "path" ]
[ 355, 4 ]
[ 357, 19 ]
python
en
['en', 'en', 'en']
True
AbstractSandbox._remap_input
(self, operation, path, *args, **kw)
Called for path inputs
Called for path inputs
def _remap_input(self, operation, path, *args, **kw): """Called for path inputs""" return self._validate_path(path)
[ "def", "_remap_input", "(", "self", ",", "operation", ",", "path", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "return", "self", ".", "_validate_path", "(", "path", ")" ]
[ 359, 4 ]
[ 361, 40 ]
python
en
['en', 'en', 'en']
True
AbstractSandbox._remap_output
(self, operation, path)
Called for path outputs
Called for path outputs
def _remap_output(self, operation, path): """Called for path outputs""" return self._validate_path(path)
[ "def", "_remap_output", "(", "self", ",", "operation", ",", "path", ")", ":", "return", "self", ".", "_validate_path", "(", "path", ")" ]
[ 363, 4 ]
[ 365, 40 ]
python
en
['en', 'en', 'en']
True
AbstractSandbox._remap_pair
(self, operation, src, dst, *args, **kw)
Called for path pairs like rename, link, and symlink operations
Called for path pairs like rename, link, and symlink operations
def _remap_pair(self, operation, src, dst, *args, **kw): """Called for path pairs like rename, link, and symlink operations""" return ( self._remap_input(operation + '-from', src, *args, **kw), self._remap_input(operation + '-to', dst, *args, **kw) )
[ "def", "_remap_pair", "(", "self", ",", "operation", ",", "src", ",", "dst", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "return", "(", "self", ".", "_remap_input", "(", "operation", "+", "'-from'", ",", "src", ",", "*", "args", ",", "*", "*...
[ 367, 4 ]
[ 372, 9 ]
python
en
['en', 'en', 'en']
True
DirectorySandbox._remap_input
(self, operation, path, *args, **kw)
Called for path inputs
Called for path inputs
def _remap_input(self, operation, path, *args, **kw): """Called for path inputs""" if operation in self.write_ops and not self._ok(path): self._violation(operation, os.path.realpath(path), *args, **kw) return path
[ "def", "_remap_input", "(", "self", ",", "operation", ",", "path", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "if", "operation", "in", "self", ".", "write_ops", "and", "not", "self", ".", "_ok", "(", "path", ")", ":", "self", ".", "_violation...
[ 448, 4 ]
[ 452, 19 ]
python
en
['en', 'en', 'en']
True
DirectorySandbox._remap_pair
(self, operation, src, dst, *args, **kw)
Called for path pairs like rename, link, and symlink operations
Called for path pairs like rename, link, and symlink operations
def _remap_pair(self, operation, src, dst, *args, **kw): """Called for path pairs like rename, link, and symlink operations""" if not self._ok(src) or not self._ok(dst): self._violation(operation, src, dst, *args, **kw) return (src, dst)
[ "def", "_remap_pair", "(", "self", ",", "operation", ",", "src", ",", "dst", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "if", "not", "self", ".", "_ok", "(", "src", ")", "or", "not", "self", ".", "_ok", "(", "dst", ")", ":", "self", "."...
[ 454, 4 ]
[ 458, 25 ]
python
en
['en', 'en', 'en']
True
DirectorySandbox.open
(self, file, flags, mode=0o777, *args, **kw)
Called for low-level os.open()
Called for low-level os.open()
def open(self, file, flags, mode=0o777, *args, **kw): """Called for low-level os.open()""" if flags & WRITE_FLAGS and not self._ok(file): self._violation("os.open", file, flags, mode, *args, **kw) return _os.open(file, flags, mode, *args, **kw)
[ "def", "open", "(", "self", ",", "file", ",", "flags", ",", "mode", "=", "0o777", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "if", "flags", "&", "WRITE_FLAGS", "and", "not", "self", ".", "_ok", "(", "file", ")", ":", "self", ".", "_violat...
[ 460, 4 ]
[ 464, 55 ]
python
en
['en', 'en', 'en']
True
transform
(data, ops=[])
transform
transform
def transform(data, ops=[]): """ transform """ for op in ops: data = op(data) return data
[ "def", "transform", "(", "data", ",", "ops", "=", "[", "]", ")", ":", "for", "op", "in", "ops", ":", "data", "=", "op", "(", "data", ")", "return", "data" ]
[ 39, 0 ]
[ 43, 15 ]
python
en
['en', 'ru', 'en']
False
wsgi_to_bytes
(data)
coerce wsgi unicode represented bytes to real ones
coerce wsgi unicode represented bytes to real ones
def wsgi_to_bytes(data): """coerce wsgi unicode represented bytes to real ones""" if isinstance(data, bytes): return data return data.encode("latin1")
[ "def", "wsgi_to_bytes", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "bytes", ")", ":", "return", "data", "return", "data", ".", "encode", "(", "\"latin1\"", ")" ]
[ 199, 0 ]
[ 203, 32 ]
python
en
['en', 'sn', 'en']
True
quote_header_value
(value, extra_chars="", allow_token=True)
Quote a header value if necessary. .. versionadded:: 0.5 :param value: the value to quote. :param extra_chars: a list of extra characters to skip quoting. :param allow_token: if this is enabled token values are returned unchanged.
Quote a header value if necessary.
def quote_header_value(value, extra_chars="", allow_token=True): """Quote a header value if necessary. .. versionadded:: 0.5 :param value: the value to quote. :param extra_chars: a list of extra characters to skip quoting. :param allow_token: if this is enabled token values are returned ...
[ "def", "quote_header_value", "(", "value", ",", "extra_chars", "=", "\"\"", ",", "allow_token", "=", "True", ")", ":", "if", "isinstance", "(", "value", ",", "bytes", ")", ":", "value", "=", "bytes_to_wsgi", "(", "value", ")", "value", "=", "str", "(", ...
[ 214, 0 ]
[ 231, 67 ]
python
en
['en', 'en', 'en']
True
unquote_header_value
(value, is_filename=False)
r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. .. versionadded:: 0.5 :param value: the header value to unquote.
r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting.
def unquote_header_value(value, is_filename=False): r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. .. versionadded:: 0.5 :param value: the header value to unquote. """ if value a...
[ "def", "unquote_header_value", "(", "value", ",", "is_filename", "=", "False", ")", ":", "if", "value", "and", "value", "[", "0", "]", "==", "value", "[", "-", "1", "]", "==", "'\"'", ":", "# this is not the real unquoting, but fixing this so that the", "# RFC i...
[ 234, 0 ]
[ 257, 16 ]
python
en
['en', 'en', 'en']
True
dump_options_header
(header, options)
The reverse function to :func:`parse_options_header`. :param header: the header to dump :param options: a dict of options to append.
The reverse function to :func:`parse_options_header`.
def dump_options_header(header, options): """The reverse function to :func:`parse_options_header`. :param header: the header to dump :param options: a dict of options to append. """ segments = [] if header is not None: segments.append(header) for key, value in iteritems(options): ...
[ "def", "dump_options_header", "(", "header", ",", "options", ")", ":", "segments", "=", "[", "]", "if", "header", "is", "not", "None", ":", "segments", ".", "append", "(", "header", ")", "for", "key", ",", "value", "in", "iteritems", "(", "options", ")...
[ 260, 0 ]
[ 274, 30 ]
python
en
['en', 'en', 'en']
True
dump_header
(iterable, allow_token=True)
Dump an HTTP header again. This is the reversal of :func:`parse_list_header`, :func:`parse_set_header` and :func:`parse_dict_header`. This also quotes strings that include an equals sign unless you pass it as dict of key, value pairs. >>> dump_header({'foo': 'bar baz'}) 'foo="bar baz"' >>> du...
Dump an HTTP header again. This is the reversal of :func:`parse_list_header`, :func:`parse_set_header` and :func:`parse_dict_header`. This also quotes strings that include an equals sign unless you pass it as dict of key, value pairs.
def dump_header(iterable, allow_token=True): """Dump an HTTP header again. This is the reversal of :func:`parse_list_header`, :func:`parse_set_header` and :func:`parse_dict_header`. This also quotes strings that include an equals sign unless you pass it as dict of key, value pairs. >>> dump_heade...
[ "def", "dump_header", "(", "iterable", ",", "allow_token", "=", "True", ")", ":", "if", "isinstance", "(", "iterable", ",", "dict", ")", ":", "items", "=", "[", "]", "for", "key", ",", "value", "in", "iteritems", "(", "iterable", ")", ":", "if", "val...
[ 277, 0 ]
[ 303, 27 ]
python
en
['en', 'en', 'en']
True
parse_list_header
(value)
Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It ba...
Parse lists as described by RFC 2068 Section 2.
def parse_list_header(value): """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed au...
[ "def", "parse_list_header", "(", "value", ")", ":", "result", "=", "[", "]", "for", "item", "in", "_parse_list_header", "(", "value", ")", ":", "if", "item", "[", ":", "1", "]", "==", "item", "[", "-", "1", ":", "]", "==", "'\"'", ":", "item", "=...
[ 306, 0 ]
[ 333, 17 ]
python
en
['en', 'en', 'en']
True
parse_dict_header
(value, cls=dict)
Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict (or any other mapping object created from the type with a dict like interface provided by the `cls` argument): >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True ...
Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict (or any other mapping object created from the type with a dict like interface provided by the `cls` argument):
def parse_dict_header(value, cls=dict): """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict (or any other mapping object created from the type with a dict like interface provided by the `cls` argument): >>> d = parse_dict_header('foo="is a fish", ba...
[ "def", "parse_dict_header", "(", "value", ",", "cls", "=", "dict", ")", ":", "result", "=", "cls", "(", ")", "if", "not", "isinstance", "(", "value", ",", "text_type", ")", ":", "# XXX: validate", "value", "=", "bytes_to_wsgi", "(", "value", ")", "for", ...
[ 336, 0 ]
[ 374, 17 ]
python
en
['en', 'en', 'en']
True
parse_options_header
(value, multiple=False)
Parse a ``Content-Type`` like header into a tuple with the content type and the options: >>> parse_options_header('text/html; charset=utf8') ('text/html', {'charset': 'utf8'}) This should not be used to parse ``Cache-Control`` like headers that use a slightly different format. For these headers u...
Parse a ``Content-Type`` like header into a tuple with the content type and the options:
def parse_options_header(value, multiple=False): """Parse a ``Content-Type`` like header into a tuple with the content type and the options: >>> parse_options_header('text/html; charset=utf8') ('text/html', {'charset': 'utf8'}) This should not be used to parse ``Cache-Control`` like headers that u...
[ "def", "parse_options_header", "(", "value", ",", "multiple", "=", "False", ")", ":", "if", "not", "value", ":", "return", "\"\"", ",", "{", "}", "result", "=", "[", "]", "value", "=", "\",\"", "+", "value", ".", "replace", "(", "\"\\n\"", ",", "\",\...
[ 377, 0 ]
[ 446, 48 ]
python
en
['en', 'en', 'en']
True
parse_accept_header
(value, cls=None)
Parses an HTTP Accept-* header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction. Returns a new :class:`Accept` object (basically a list of ``(value, quality)`` tuples sorted by the quality with some additional accessor methods). The s...
Parses an HTTP Accept-* header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction.
def parse_accept_header(value, cls=None): """Parses an HTTP Accept-* header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction. Returns a new :class:`Accept` object (basically a list of ``(value, quality)`` tuples sorted by the quality w...
[ "def", "parse_accept_header", "(", "value", ",", "cls", "=", "None", ")", ":", "if", "cls", "is", "None", ":", "cls", "=", "Accept", "if", "not", "value", ":", "return", "cls", "(", "None", ")", "result", "=", "[", "]", "for", "match", "in", "_acce...
[ 449, 0 ]
[ 479, 22 ]
python
en
['en', 'en', 'en']
True
parse_cache_control_header
(value, on_update=None, cls=None)
Parse a cache control header. The RFC differs between response and request cache control, this method does not. It's your responsibility to not use the wrong control statements. .. versionadded:: 0.5 The `cls` was added. If not specified an immutable :class:`~werkzeug.datastructures.Reques...
Parse a cache control header. The RFC differs between response and request cache control, this method does not. It's your responsibility to not use the wrong control statements.
def parse_cache_control_header(value, on_update=None, cls=None): """Parse a cache control header. The RFC differs between response and request cache control, this method does not. It's your responsibility to not use the wrong control statements. .. versionadded:: 0.5 The `cls` was added. If n...
[ "def", "parse_cache_control_header", "(", "value", ",", "on_update", "=", "None", ",", "cls", "=", "None", ")", ":", "if", "cls", "is", "None", ":", "cls", "=", "RequestCacheControl", "if", "not", "value", ":", "return", "cls", "(", "None", ",", "on_upda...
[ 482, 0 ]
[ 503, 51 ]
python
en
['en', 'en', 'en']
True
parse_set_header
(value, on_update=None)
Parse a set-like header and return a :class:`~werkzeug.datastructures.HeaderSet` object: >>> hs = parse_set_header('token, "quoted value"') The return value is an object that treats the items case-insensitively and keeps the order of the items: >>> 'TOKEN' in hs True >>> hs.index('quoted ...
Parse a set-like header and return a :class:`~werkzeug.datastructures.HeaderSet` object:
def parse_set_header(value, on_update=None): """Parse a set-like header and return a :class:`~werkzeug.datastructures.HeaderSet` object: >>> hs = parse_set_header('token, "quoted value"') The return value is an object that treats the items case-insensitively and keeps the order of the items: ...
[ "def", "parse_set_header", "(", "value", ",", "on_update", "=", "None", ")", ":", "if", "not", "value", ":", "return", "HeaderSet", "(", "None", ",", "on_update", ")", "return", "HeaderSet", "(", "parse_list_header", "(", "value", ")", ",", "on_update", ")...
[ 506, 0 ]
[ 533, 57 ]
python
en
['en', 'haw', 'en']
True
parse_authorization_header
(value)
Parse an HTTP basic/digest authorization header transmitted by the web browser. The return value is either `None` if the header was invalid or not given, otherwise an :class:`~werkzeug.datastructures.Authorization` object. :param value: the authorization header to parse. :return: a :class:`~werkze...
Parse an HTTP basic/digest authorization header transmitted by the web browser. The return value is either `None` if the header was invalid or not given, otherwise an :class:`~werkzeug.datastructures.Authorization` object.
def parse_authorization_header(value): """Parse an HTTP basic/digest authorization header transmitted by the web browser. The return value is either `None` if the header was invalid or not given, otherwise an :class:`~werkzeug.datastructures.Authorization` object. :param value: the authorization h...
[ "def", "parse_authorization_header", "(", "value", ")", ":", "if", "not", "value", ":", "return", "value", "=", "wsgi_to_bytes", "(", "value", ")", "try", ":", "auth_type", ",", "auth_info", "=", "value", ".", "split", "(", "None", ",", "1", ")", "auth_t...
[ 536, 0 ]
[ 573, 48 ]
python
en
['en', 'en', 'en']
True
parse_www_authenticate_header
(value, on_update=None)
Parse an HTTP WWW-Authenticate header into a :class:`~werkzeug.datastructures.WWWAuthenticate` object. :param value: a WWW-Authenticate header to parse. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.WWWAuthenticate` ...
Parse an HTTP WWW-Authenticate header into a :class:`~werkzeug.datastructures.WWWAuthenticate` object.
def parse_www_authenticate_header(value, on_update=None): """Parse an HTTP WWW-Authenticate header into a :class:`~werkzeug.datastructures.WWWAuthenticate` object. :param value: a WWW-Authenticate header to parse. :param on_update: an optional callable that is called every time a value ...
[ "def", "parse_www_authenticate_header", "(", "value", ",", "on_update", "=", "None", ")", ":", "if", "not", "value", ":", "return", "WWWAuthenticate", "(", "on_update", "=", "on_update", ")", "try", ":", "auth_type", ",", "auth_info", "=", "value", ".", "spl...
[ 576, 0 ]
[ 593, 78 ]
python
en
['en', 'en', 'en']
True
parse_if_range_header
(value)
Parses an if-range header which can be an etag or a date. Returns a :class:`~werkzeug.datastructures.IfRange` object. .. versionadded:: 0.7
Parses an if-range header which can be an etag or a date. Returns a :class:`~werkzeug.datastructures.IfRange` object.
def parse_if_range_header(value): """Parses an if-range header which can be an etag or a date. Returns a :class:`~werkzeug.datastructures.IfRange` object. .. versionadded:: 0.7 """ if not value: return IfRange() date = parse_date(value) if date is not None: return IfRange(d...
[ "def", "parse_if_range_header", "(", "value", ")", ":", "if", "not", "value", ":", "return", "IfRange", "(", ")", "date", "=", "parse_date", "(", "value", ")", "if", "date", "is", "not", "None", ":", "return", "IfRange", "(", "date", "=", "date", ")", ...
[ 596, 0 ]
[ 608, 42 ]
python
en
['en', 'en', 'en']
True
parse_range_header
(value, make_inclusive=True)
Parses a range header into a :class:`~werkzeug.datastructures.Range` object. If the header is missing or malformed `None` is returned. `ranges` is a list of ``(start, stop)`` tuples where the ranges are non-inclusive. .. versionadded:: 0.7
Parses a range header into a :class:`~werkzeug.datastructures.Range` object. If the header is missing or malformed `None` is returned. `ranges` is a list of ``(start, stop)`` tuples where the ranges are non-inclusive.
def parse_range_header(value, make_inclusive=True): """Parses a range header into a :class:`~werkzeug.datastructures.Range` object. If the header is missing or malformed `None` is returned. `ranges` is a list of ``(start, stop)`` tuples where the ranges are non-inclusive. .. versionadded:: 0.7 ...
[ "def", "parse_range_header", "(", "value", ",", "make_inclusive", "=", "True", ")", ":", "if", "not", "value", "or", "\"=\"", "not", "in", "value", ":", "return", "None", "ranges", "=", "[", "]", "last_end", "=", "0", "units", ",", "rng", "=", "value",...
[ 611, 0 ]
[ 660, 31 ]
python
en
['en', 'de', 'en']
True
parse_content_range_header
(value, on_update=None)
Parses a range header into a :class:`~werkzeug.datastructures.ContentRange` object or `None` if parsing is not possible. .. versionadded:: 0.7 :param value: a content range header to be parsed. :param on_update: an optional callable that is called every time a value on the :c...
Parses a range header into a :class:`~werkzeug.datastructures.ContentRange` object or `None` if parsing is not possible.
def parse_content_range_header(value, on_update=None): """Parses a range header into a :class:`~werkzeug.datastructures.ContentRange` object or `None` if parsing is not possible. .. versionadded:: 0.7 :param value: a content range header to be parsed. :param on_update: an optional callable tha...
[ "def", "parse_content_range_header", "(", "value", ",", "on_update", "=", "None", ")", ":", "if", "value", "is", "None", ":", "return", "None", "try", ":", "units", ",", "rangedef", "=", "(", "value", "or", "\"\"", ")", ".", "strip", "(", ")", ".", "...
[ 663, 0 ]
[ 705, 76 ]
python
en
['en', 'en', 'en']
True
quote_etag
(etag, weak=False)
Quote an etag. :param etag: the etag to quote. :param weak: set to `True` to tag it "weak".
Quote an etag.
def quote_etag(etag, weak=False): """Quote an etag. :param etag: the etag to quote. :param weak: set to `True` to tag it "weak". """ if '"' in etag: raise ValueError("invalid etag") etag = '"%s"' % etag if weak: etag = "W/" + etag return etag
[ "def", "quote_etag", "(", "etag", ",", "weak", "=", "False", ")", ":", "if", "'\"'", "in", "etag", ":", "raise", "ValueError", "(", "\"invalid etag\"", ")", "etag", "=", "'\"%s\"'", "%", "etag", "if", "weak", ":", "etag", "=", "\"W/\"", "+", "etag", ...
[ 708, 0 ]
[ 719, 15 ]
python
en
['en', 'en', 'es']
True
unquote_etag
(etag)
Unquote a single etag: >>> unquote_etag('W/"bar"') ('bar', True) >>> unquote_etag('"bar"') ('bar', False) :param etag: the etag identifier to unquote. :return: a ``(etag, weak)`` tuple.
Unquote a single etag:
def unquote_etag(etag): """Unquote a single etag: >>> unquote_etag('W/"bar"') ('bar', True) >>> unquote_etag('"bar"') ('bar', False) :param etag: the etag identifier to unquote. :return: a ``(etag, weak)`` tuple. """ if not etag: return None, None etag = etag.strip() ...
[ "def", "unquote_etag", "(", "etag", ")", ":", "if", "not", "etag", ":", "return", "None", ",", "None", "etag", "=", "etag", ".", "strip", "(", ")", "weak", "=", "False", "if", "etag", ".", "startswith", "(", "(", "\"W/\"", ",", "\"w/\"", ")", ")", ...
[ 722, 0 ]
[ 742, 21 ]
python
fr
['fr', 'it', 'pt']
False
parse_etags
(value)
Parse an etag header. :param value: the tag header to parse :return: an :class:`~werkzeug.datastructures.ETags` object.
Parse an etag header.
def parse_etags(value): """Parse an etag header. :param value: the tag header to parse :return: an :class:`~werkzeug.datastructures.ETags` object. """ if not value: return ETags() strong = [] weak = [] end = len(value) pos = 0 while pos < end: match = _etag_re.ma...
[ "def", "parse_etags", "(", "value", ")", ":", "if", "not", "value", ":", "return", "ETags", "(", ")", "strong", "=", "[", "]", "weak", "=", "[", "]", "end", "=", "len", "(", "value", ")", "pos", "=", "0", "while", "pos", "<", "end", ":", "match...
[ 745, 0 ]
[ 771, 30 ]
python
br
['br', 'gd', 'es']
False
generate_etag
(data)
Generate an etag for some data.
Generate an etag for some data.
def generate_etag(data): """Generate an etag for some data.""" return md5(data).hexdigest()
[ "def", "generate_etag", "(", "data", ")", ":", "return", "md5", "(", "data", ")", ".", "hexdigest", "(", ")" ]
[ 774, 0 ]
[ 776, 32 ]
python
en
['no', 'en', 'es']
False