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
SubmissionValidator._extract_submission
(self, filename)
Extracts submission and moves it into self._extracted_submission_dir.
Extracts submission and moves it into self._extracted_submission_dir.
def _extract_submission(self, filename): """Extracts submission and moves it into self._extracted_submission_dir.""" # verify filesize file_size = os.path.getsize(filename) if file_size > MAX_SUBMISSION_SIZE_ZIPPED: logging.error( "Submission archive size %d i...
[ "def", "_extract_submission", "(", "self", ",", "filename", ")", ":", "# verify filesize", "file_size", "=", "os", ".", "path", ".", "getsize", "(", "filename", ")", "if", "file_size", ">", "MAX_SUBMISSION_SIZE_ZIPPED", ":", "logging", ".", "error", "(", "\"Su...
[ 151, 4 ]
[ 212, 19 ]
python
en
['en', 'en', 'en']
True
SubmissionValidator._load_and_verify_metadata
(self, submission_type)
Loads and verifies metadata. Args: submission_type: type of the submission Returns: dictionaty with metadata or None if metadata not found or invalid
Loads and verifies metadata.
def _load_and_verify_metadata(self, submission_type): """Loads and verifies metadata. Args: submission_type: type of the submission Returns: dictionaty with metadata or None if metadata not found or invalid """ metadata_filename = os.path.join( s...
[ "def", "_load_and_verify_metadata", "(", "self", ",", "submission_type", ")", ":", "metadata_filename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_extracted_submission_dir", ",", "\"metadata.json\"", ")", "if", "not", "os", ".", "path", ".", "isf...
[ 226, 4 ]
[ 275, 23 ]
python
en
['en', 'mi', 'en']
True
SubmissionValidator._verify_docker_image_size
(self, image_name)
Verifies size of Docker image. Args: image_name: name of the Docker image. Returns: True if image size is withing the limits, False otherwise.
Verifies size of Docker image.
def _verify_docker_image_size(self, image_name): """Verifies size of Docker image. Args: image_name: name of the Docker image. Returns: True if image size is withing the limits, False otherwise. """ shell_call(["docker", "pull", image_name]) try: ...
[ "def", "_verify_docker_image_size", "(", "self", ",", "image_name", ")", ":", "shell_call", "(", "[", "\"docker\"", ",", "\"pull\"", ",", "image_name", "]", ")", "try", ":", "image_size", "=", "subprocess", ".", "check_output", "(", "[", "\"docker\"", ",", "...
[ 277, 4 ]
[ 298, 50 ]
python
en
['en', 'jv', 'en']
True
SubmissionValidator._prepare_sample_data
(self, submission_type)
Prepares sample data for the submission. Args: submission_type: type of the submission.
Prepares sample data for the submission.
def _prepare_sample_data(self, submission_type): """Prepares sample data for the submission. Args: submission_type: type of the submission. """ # write images images = np.random.randint( 0, 256, size=[BATCH_SIZE, 299, 299, 3], dtype=np.uint8 ) ...
[ "def", "_prepare_sample_data", "(", "self", ",", "submission_type", ")", ":", "# write images", "images", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "256", ",", "size", "=", "[", "BATCH_SIZE", ",", "299", ",", "299", ",", "3", "]", ",", ...
[ 300, 4 ]
[ 324, 21 ]
python
en
['en', 'en', 'en']
True
SubmissionValidator._run_submission
(self, metadata)
Runs submission inside Docker container. Args: metadata: dictionary with submission metadata Returns: True if status code of Docker command was success (i.e. zero), False otherwise.
Runs submission inside Docker container.
def _run_submission(self, metadata): """Runs submission inside Docker container. Args: metadata: dictionary with submission metadata Returns: True if status code of Docker command was success (i.e. zero), False otherwise. """ if self._use_gpu: ...
[ "def", "_run_submission", "(", "self", ",", "metadata", ")", ":", "if", "self", ".", "_use_gpu", ":", "docker_binary", "=", "\"nvidia-docker\"", "container_name", "=", "metadata", "[", "\"container_gpu\"", "]", "else", ":", "docker_binary", "=", "\"docker\"", "c...
[ 326, 4 ]
[ 383, 30 ]
python
en
['en', 'en', 'en']
True
SubmissionValidator._verify_output
(self, submission_type)
Verifies correctness of the submission output. Args: submission_type: type of the submission Returns: True if output looks valid
Verifies correctness of the submission output.
def _verify_output(self, submission_type): """Verifies correctness of the submission output. Args: submission_type: type of the submission Returns: True if output looks valid """ result = True if submission_type == "defense": try: ...
[ "def", "_verify_output", "(", "self", ",", "submission_type", ")", ":", "result", "=", "True", "if", "submission_type", "==", "\"defense\"", ":", "try", ":", "image_classification", "=", "load_defense_output", "(", "os", ".", "path", ".", "join", "(", "self", ...
[ 385, 4 ]
[ 425, 21 ]
python
en
['en', 'en', 'en']
True
SubmissionValidator.validate_submission
(self, filename, submission_type)
Validates submission. Args: filename: submission filename submission_type: type of the submission, one of 'attack', 'targeted_attack' or 'defense' Returns: whether submission is valid
Validates submission.
def validate_submission(self, filename, submission_type): """Validates submission. Args: filename: submission filename submission_type: type of the submission, one of 'attack', 'targeted_attack' or 'defense' Returns: whether submission is valid ...
[ "def", "validate_submission", "(", "self", ",", "filename", ",", "submission_type", ")", ":", "if", "submission_type", "not", "in", "ALLOWED_SUBMISSION_TYPES", ":", "logging", ".", "error", "(", "\"Invalid submission type: %s\"", ",", "submission_type", ")", "return",...
[ 427, 4 ]
[ 469, 19 ]
python
en
['fr', 'la', 'en']
False
MessageMiddleware.process_response
(self, request, response)
Updates the storage backend (i.e., saves the messages). If not all messages could not be stored and ``DEBUG`` is ``True``, a ``ValueError`` is raised.
Updates the storage backend (i.e., saves the messages).
def process_response(self, request, response): """ Updates the storage backend (i.e., saves the messages). If not all messages could not be stored and ``DEBUG`` is ``True``, a ``ValueError`` is raised. """ # A higher middleware layer may return a request which does not c...
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "# A higher middleware layer may return a request which does not contain", "# messages storage, so make no assumption that it will be there.", "if", "hasattr", "(", "request", ",", "'_messages'", "...
[ 12, 4 ]
[ 25, 23 ]
python
en
['en', 'error', 'th']
False
select_related_descend
(field, restricted, requested, load_fields, reverse=False)
Returns True if this field should be used to descend deeper for select_related() purposes. Used by both the query construction code (sql.query.fill_related_selections()) and the model instance creation code (query.get_klass_info()). Arguments: * field - the field to be checked * restrict...
Returns True if this field should be used to descend deeper for select_related() purposes. Used by both the query construction code (sql.query.fill_related_selections()) and the model instance creation code (query.get_klass_info()).
def select_related_descend(field, restricted, requested, load_fields, reverse=False): """ Returns True if this field should be used to descend deeper for select_related() purposes. Used by both the query construction code (sql.query.fill_related_selections()) and the model instance creation code (qu...
[ "def", "select_related_descend", "(", "field", ",", "restricted", ",", "requested", ",", "load_fields", ",", "reverse", "=", "False", ")", ":", "if", "not", "field", ".", "rel", ":", "return", "False", "if", "field", ".", "rel", ".", "parent_link", "and", ...
[ 142, 0 ]
[ 176, 15 ]
python
en
['en', 'error', 'th']
False
deferred_class_factory
(model, attrs)
Returns a class object that is a copy of "model" with the specified "attrs" being replaced with DeferredAttribute objects. The "pk_value" ties the deferred attributes to a particular instance of the model.
Returns a class object that is a copy of "model" with the specified "attrs" being replaced with DeferredAttribute objects. The "pk_value" ties the deferred attributes to a particular instance of the model.
def deferred_class_factory(model, attrs): """ Returns a class object that is a copy of "model" with the specified "attrs" being replaced with DeferredAttribute objects. The "pk_value" ties the deferred attributes to a particular instance of the model. """ if not attrs: return model #...
[ "def", "deferred_class_factory", "(", "model", ",", "attrs", ")", ":", "if", "not", "attrs", ":", "return", "model", "# Never create deferred models based on deferred model", "if", "model", ".", "_deferred", ":", "# Deferred models are proxies for the non-deferred model. We n...
[ 182, 0 ]
[ 216, 51 ]
python
en
['en', 'error', 'th']
False
DeferredAttribute.__get__
(self, instance, owner)
Retrieves and caches the value from the datastore on the first lookup. Returns the cached value.
Retrieves and caches the value from the datastore on the first lookup. Returns the cached value.
def __get__(self, instance, owner): """ Retrieves and caches the value from the datastore on the first lookup. Returns the cached value. """ from django.db.models.fields import FieldDoesNotExist non_deferred_model = instance._meta.proxy_for_model opts = non_deferr...
[ "def", "__get__", "(", "self", ",", "instance", ",", "owner", ")", ":", "from", "django", ".", "db", ".", "models", ".", "fields", "import", "FieldDoesNotExist", "non_deferred_model", "=", "instance", ".", "_meta", ".", "proxy_for_model", "opts", "=", "non_d...
[ 87, 4 ]
[ 119, 36 ]
python
en
['en', 'error', 'th']
False
DeferredAttribute.__set__
(self, instance, value)
Deferred loading attributes can be set normally (which means there will never be a database lookup involved.
Deferred loading attributes can be set normally (which means there will never be a database lookup involved.
def __set__(self, instance, value): """ Deferred loading attributes can be set normally (which means there will never be a database lookup involved. """ instance.__dict__[self.field_name] = value
[ "def", "__set__", "(", "self", ",", "instance", ",", "value", ")", ":", "instance", ".", "__dict__", "[", "self", ".", "field_name", "]", "=", "value" ]
[ 121, 4 ]
[ 126, 50 ]
python
en
['en', 'error', 'th']
False
DeferredAttribute._check_parent_chain
(self, instance, name)
Check if the field value can be fetched from a parent field already loaded in the instance. This can be done if the to-be fetched field is a primary key field.
Check if the field value can be fetched from a parent field already loaded in the instance. This can be done if the to-be fetched field is a primary key field.
def _check_parent_chain(self, instance, name): """ Check if the field value can be fetched from a parent field already loaded in the instance. This can be done if the to-be fetched field is a primary key field. """ opts = instance._meta f = opts.get_field_by_name(...
[ "def", "_check_parent_chain", "(", "self", ",", "instance", ",", "name", ")", ":", "opts", "=", "instance", ".", "_meta", "f", "=", "opts", ".", "get_field_by_name", "(", "name", ")", "[", "0", "]", "link_field", "=", "opts", ".", "get_ancestor_link", "(...
[ 128, 4 ]
[ 139, 19 ]
python
en
['en', 'error', 'th']
False
dbl_from_geom
(func, num_geom=1)
Argument is a Geometry, return type is double that is passed in by reference as the last argument.
Argument is a Geometry, return type is double that is passed in by reference as the last argument.
def dbl_from_geom(func, num_geom=1): """ Argument is a Geometry, return type is double that is passed in by reference as the last argument. """ argtypes = [GEOM_PTR for i in xrange(num_geom)] argtypes += [POINTER(c_double)] func.argtypes = argtypes func.restype = c_int # Status code ret...
[ "def", "dbl_from_geom", "(", "func", ",", "num_geom", "=", "1", ")", ":", "argtypes", "=", "[", "GEOM_PTR", "for", "i", "in", "xrange", "(", "num_geom", ")", "]", "argtypes", "+=", "[", "POINTER", "(", "c_double", ")", "]", "func", ".", "argtypes", "...
[ 15, 0 ]
[ 25, 15 ]
python
en
['en', 'error', 'th']
False
EmailBackend.send_messages
(self, email_messages)
Write all messages to the stream in a thread-safe way.
Write all messages to the stream in a thread-safe way.
def send_messages(self, email_messages): """Write all messages to the stream in a thread-safe way.""" if not email_messages: return msg_count = 0 with self._lock: try: stream_created = self.open() for message in email_messages: ...
[ "def", "send_messages", "(", "self", ",", "email_messages", ")", ":", "if", "not", "email_messages", ":", "return", "msg_count", "=", "0", "with", "self", ".", "_lock", ":", "try", ":", "stream_created", "=", "self", ".", "open", "(", ")", "for", "messag...
[ 24, 4 ]
[ 41, 24 ]
python
en
['en', 'en', 'en']
True
patch_path
(path)
Add path to front of sys.path for the duration of the context.
Add path to front of sys.path for the duration of the context.
def patch_path(path): """ Add path to front of sys.path for the duration of the context. """ try: sys.path.insert(0, path) yield finally: sys.path.remove(path)
[ "def", "patch_path", "(", "path", ")", ":", "try", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "path", ")", "yield", "finally", ":", "sys", ".", "path", ".", "remove", "(", "path", ")" ]
[ 51, 0 ]
[ 59, 29 ]
python
en
['en', 'error', 'th']
False
read_configuration
( filepath, find_others=False, ignore_option_errors=False)
Read given configuration file and returns options from it as a dict. :param str|unicode filepath: Path to configuration file to get options from. :param bool find_others: Whether to search for other configuration files which could be on in various places. :param bool ignore_option_errors:...
Read given configuration file and returns options from it as a dict.
def read_configuration( filepath, find_others=False, ignore_option_errors=False): """Read given configuration file and returns options from it as a dict. :param str|unicode filepath: Path to configuration file to get options from. :param bool find_others: Whether to search for other config...
[ "def", "read_configuration", "(", "filepath", ",", "find_others", "=", "False", ",", "ignore_option_errors", "=", "False", ")", ":", "from", "setuptools", ".", "dist", "import", "Distribution", ",", "_Distribution", "filepath", "=", "os", ".", "path", ".", "ab...
[ 62, 0 ]
[ 106, 42 ]
python
en
['en', 'en', 'en']
True
_get_option
(target_obj, key)
Given a target object and option key, get that option from the target object, either through a get_{key} method or from an attribute directly.
Given a target object and option key, get that option from the target object, either through a get_{key} method or from an attribute directly.
def _get_option(target_obj, key): """ Given a target object and option key, get that option from the target object, either through a get_{key} method or from an attribute directly. """ getter_name = 'get_{key}'.format(**locals()) by_attribute = functools.partial(getattr, target_obj, key) ...
[ "def", "_get_option", "(", "target_obj", ",", "key", ")", ":", "getter_name", "=", "'get_{key}'", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "by_attribute", "=", "functools", ".", "partial", "(", "getattr", ",", "target_obj", ",", "key", ")",...
[ 109, 0 ]
[ 118, 19 ]
python
en
['en', 'error', 'th']
False
configuration_to_dict
(handlers)
Returns configuration data gathered by given handlers as a dict. :param list[ConfigHandler] handlers: Handlers list, usually from parse_configuration() :rtype: dict
Returns configuration data gathered by given handlers as a dict.
def configuration_to_dict(handlers): """Returns configuration data gathered by given handlers as a dict. :param list[ConfigHandler] handlers: Handlers list, usually from parse_configuration() :rtype: dict """ config_dict = defaultdict(dict) for handler in handlers: for option ...
[ "def", "configuration_to_dict", "(", "handlers", ")", ":", "config_dict", "=", "defaultdict", "(", "dict", ")", "for", "handler", "in", "handlers", ":", "for", "option", "in", "handler", ".", "set_options", ":", "value", "=", "_get_option", "(", "handler", "...
[ 121, 0 ]
[ 136, 22 ]
python
en
['en', 'en', 'en']
True
parse_configuration
( distribution, command_options, ignore_option_errors=False)
Performs additional parsing of configuration options for a distribution. Returns a list of used option handlers. :param Distribution distribution: :param dict command_options: :param bool ignore_option_errors: Whether to silently ignore options, values of which could not be resolved (e.g. ...
Performs additional parsing of configuration options for a distribution.
def parse_configuration( distribution, command_options, ignore_option_errors=False): """Performs additional parsing of configuration options for a distribution. Returns a list of used option handlers. :param Distribution distribution: :param dict command_options: :param bool ignore_opt...
[ "def", "parse_configuration", "(", "distribution", ",", "command_options", ",", "ignore_option_errors", "=", "False", ")", ":", "options", "=", "ConfigOptionsHandler", "(", "distribution", ",", "command_options", ",", "ignore_option_errors", ")", "options", ".", "pars...
[ 139, 0 ]
[ 163, 24 ]
python
en
['en', 'en', 'en']
True
ConfigHandler.parsers
(self)
Metadata item name to parser function mapping.
Metadata item name to parser function mapping.
def parsers(self): """Metadata item name to parser function mapping.""" raise NotImplementedError( '%s must provide .parsers property' % self.__class__.__name__)
[ "def", "parsers", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'%s must provide .parsers property'", "%", "self", ".", "__class__", ".", "__name__", ")" ]
[ 199, 4 ]
[ 202, 74 ]
python
en
['en', 'jv', 'en']
True
ConfigHandler._parse_list
(cls, value, separator=',')
Represents value as a list. Value is split either by separator (defaults to comma) or by lines. :param value: :param separator: List items separator character. :rtype: list
Represents value as a list.
def _parse_list(cls, value, separator=','): """Represents value as a list. Value is split either by separator (defaults to comma) or by lines. :param value: :param separator: List items separator character. :rtype: list """ if isinstance(value, list): # _get_pa...
[ "def", "_parse_list", "(", "cls", ",", "value", ",", "separator", "=", "','", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "# _get_parser_compound case", "return", "value", "if", "'\\n'", "in", "value", ":", "value", "=", "value", "...
[ 243, 4 ]
[ 260, 66 ]
python
en
['en', 'en', 'en']
True
ConfigHandler._parse_dict
(cls, value)
Represents value as a dict. :param value: :rtype: dict
Represents value as a dict.
def _parse_dict(cls, value): """Represents value as a dict. :param value: :rtype: dict """ separator = '=' result = {} for line in cls._parse_list(value): key, sep, val = line.partition(separator) if sep != separator: raise...
[ "def", "_parse_dict", "(", "cls", ",", "value", ")", ":", "separator", "=", "'='", "result", "=", "{", "}", "for", "line", "in", "cls", ".", "_parse_list", "(", "value", ")", ":", "key", ",", "sep", ",", "val", "=", "line", ".", "partition", "(", ...
[ 263, 4 ]
[ 278, 21 ]
python
en
['en', 'ca', 'en']
True
ConfigHandler._parse_bool
(cls, value)
Represents value as boolean. :param value: :rtype: bool
Represents value as boolean.
def _parse_bool(cls, value): """Represents value as boolean. :param value: :rtype: bool """ value = value.lower() return value in ('1', 'true', 'yes')
[ "def", "_parse_bool", "(", "cls", ",", "value", ")", ":", "value", "=", "value", ".", "lower", "(", ")", "return", "value", "in", "(", "'1'", ",", "'true'", ",", "'yes'", ")" ]
[ 281, 4 ]
[ 288, 44 ]
python
en
['en', 'en', 'en']
True
ConfigHandler._exclude_files_parser
(cls, key)
Returns a parser function to make sure field inputs are not files. Parses a value after getting the key so error messages are more informative. :param key: :rtype: callable
Returns a parser function to make sure field inputs are not files.
def _exclude_files_parser(cls, key): """Returns a parser function to make sure field inputs are not files. Parses a value after getting the key so error messages are more informative. :param key: :rtype: callable """ def parser(value): exclud...
[ "def", "_exclude_files_parser", "(", "cls", ",", "key", ")", ":", "def", "parser", "(", "value", ")", ":", "exclude_directive", "=", "'file:'", "if", "value", ".", "startswith", "(", "exclude_directive", ")", ":", "raise", "ValueError", "(", "'Only strings are...
[ 291, 4 ]
[ 308, 21 ]
python
en
['en', 'en', 'en']
True
ConfigHandler._parse_file
(cls, value)
Represents value as a string, allowing including text from nearest files using `file:` directive. Directive is sandboxed and won't reach anything outside directory with setup.py. Examples: file: README.rst, CHANGELOG.md, src/file.txt :param str value: :rtyp...
Represents value as a string, allowing including text from nearest files using `file:` directive.
def _parse_file(cls, value): """Represents value as a string, allowing including text from nearest files using `file:` directive. Directive is sandboxed and won't reach anything outside directory with setup.py. Examples: file: README.rst, CHANGELOG.md, src/file.txt ...
[ "def", "_parse_file", "(", "cls", ",", "value", ")", ":", "include_directive", "=", "'file:'", "if", "not", "isinstance", "(", "value", ",", "string_types", ")", ":", "return", "value", "if", "not", "value", ".", "startswith", "(", "include_directive", ")", ...
[ 311, 4 ]
[ 339, 9 ]
python
en
['en', 'en', 'en']
True
ConfigHandler._parse_attr
(cls, value, package_dir=None)
Represents value as a module attribute. Examples: attr: package.attr attr: package.module.attr :param str value: :rtype: str
Represents value as a module attribute.
def _parse_attr(cls, value, package_dir=None): """Represents value as a module attribute. Examples: attr: package.attr attr: package.module.attr :param str value: :rtype: str """ attr_directive = 'attr:' if not value.startswith(attr_direc...
[ "def", "_parse_attr", "(", "cls", ",", "value", ",", "package_dir", "=", "None", ")", ":", "attr_directive", "=", "'attr:'", "if", "not", "value", ".", "startswith", "(", "attr_directive", ")", ":", "return", "value", "attrs_path", "=", "value", ".", "repl...
[ 353, 4 ]
[ 396, 41 ]
python
en
['en', 'en', 'en']
True
ConfigHandler._get_parser_compound
(cls, *parse_methods)
Returns parser function to represents value as a list. Parses a value applying given methods one after another. :param parse_methods: :rtype: callable
Returns parser function to represents value as a list.
def _get_parser_compound(cls, *parse_methods): """Returns parser function to represents value as a list. Parses a value applying given methods one after another. :param parse_methods: :rtype: callable """ def parse(value): parsed = value for met...
[ "def", "_get_parser_compound", "(", "cls", ",", "*", "parse_methods", ")", ":", "def", "parse", "(", "value", ")", ":", "parsed", "=", "value", "for", "method", "in", "parse_methods", ":", "parsed", "=", "method", "(", "parsed", ")", "return", "parsed", ...
[ 399, 4 ]
[ 415, 20 ]
python
en
['en', 'en', 'en']
True
ConfigHandler._parse_section_to_dict
(cls, section_options, values_parser=None)
Parses section options into a dictionary. Optionally applies a given parser to values. :param dict section_options: :param callable values_parser: :rtype: dict
Parses section options into a dictionary.
def _parse_section_to_dict(cls, section_options, values_parser=None): """Parses section options into a dictionary. Optionally applies a given parser to values. :param dict section_options: :param callable values_parser: :rtype: dict """ value = {} values...
[ "def", "_parse_section_to_dict", "(", "cls", ",", "section_options", ",", "values_parser", "=", "None", ")", ":", "value", "=", "{", "}", "values_parser", "=", "values_parser", "or", "(", "lambda", "val", ":", "val", ")", "for", "key", ",", "(", "_", ","...
[ 418, 4 ]
[ 431, 20 ]
python
en
['en', 'en', 'en']
True
ConfigHandler.parse_section
(self, section_options)
Parses configuration file section. :param dict section_options:
Parses configuration file section.
def parse_section(self, section_options): """Parses configuration file section. :param dict section_options: """ for (name, (_, value)) in section_options.items(): try: self[name] = value except KeyError: pass
[ "def", "parse_section", "(", "self", ",", "section_options", ")", ":", "for", "(", "name", ",", "(", "_", ",", "value", ")", ")", "in", "section_options", ".", "items", "(", ")", ":", "try", ":", "self", "[", "name", "]", "=", "value", "except", "K...
[ 433, 4 ]
[ 443, 20 ]
python
en
['en', 'en', 'en']
True
ConfigHandler.parse
(self)
Parses configuration file items from one or more related sections.
Parses configuration file items from one or more related sections.
def parse(self): """Parses configuration file items from one or more related sections. """ for section_name, section_options in self.sections.items(): method_postfix = '' if section_name: # [section.option] variant method_postfix = '_%s' % secti...
[ "def", "parse", "(", "self", ")", ":", "for", "section_name", ",", "section_options", "in", "self", ".", "sections", ".", "items", "(", ")", ":", "method_postfix", "=", "''", "if", "section_name", ":", "# [section.option] variant", "method_postfix", "=", "'_%s...
[ 445, 4 ]
[ 467, 50 ]
python
en
['en', 'en', 'en']
True
ConfigHandler._deprecated_config_handler
(self, func, msg, warning_class)
this function will wrap around parameters that are deprecated :param msg: deprecation message :param warning_class: class of warning exception to be raised :param func: function to be wrapped around
this function will wrap around parameters that are deprecated
def _deprecated_config_handler(self, func, msg, warning_class): """ this function will wrap around parameters that are deprecated :param msg: deprecation message :param warning_class: class of warning exception to be raised :param func: function to be wrapped around """ ...
[ "def", "_deprecated_config_handler", "(", "self", ",", "func", ",", "msg", ",", "warning_class", ")", ":", "@", "wraps", "(", "func", ")", "def", "config_handler", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "msg"...
[ 469, 4 ]
[ 481, 29 ]
python
en
['en', 'en', 'en']
True
ConfigMetadataHandler.parsers
(self)
Metadata item name to parser function mapping.
Metadata item name to parser function mapping.
def parsers(self): """Metadata item name to parser function mapping.""" parse_list = self._parse_list parse_file = self._parse_file parse_dict = self._parse_dict exclude_files_parser = self._exclude_files_parser return { 'platforms': parse_list, '...
[ "def", "parsers", "(", "self", ")", ":", "parse_list", "=", "self", ".", "_parse_list", "parse_file", "=", "self", ".", "_parse_file", "parse_dict", "=", "self", ".", "_parse_dict", "exclude_files_parser", "=", "self", ".", "_exclude_files_parser", "return", "{"...
[ 508, 4 ]
[ 532, 9 ]
python
en
['en', 'jv', 'en']
True
ConfigMetadataHandler._parse_version
(self, value)
Parses `version` option value. :param value: :rtype: str
Parses `version` option value.
def _parse_version(self, value): """Parses `version` option value. :param value: :rtype: str """ version = self._parse_file(value) if version != value: version = version.strip() # Be strict about versions loaded from file because it's easy to ...
[ "def", "_parse_version", "(", "self", ",", "value", ")", ":", "version", "=", "self", ".", "_parse_file", "(", "value", ")", "if", "version", "!=", "value", ":", "version", "=", "version", ".", "strip", "(", ")", "# Be strict about versions loaded from file be...
[ 534, 4 ]
[ 567, 22 ]
python
en
['en', 'fr', 'en']
True
ConfigOptionsHandler.parsers
(self)
Metadata item name to parser function mapping.
Metadata item name to parser function mapping.
def parsers(self): """Metadata item name to parser function mapping.""" parse_list = self._parse_list parse_list_semicolon = partial(self._parse_list, separator=';') parse_bool = self._parse_bool parse_dict = self._parse_dict return { 'zip_safe': parse_bool, ...
[ "def", "parsers", "(", "self", ")", ":", "parse_list", "=", "self", ".", "_parse_list", "parse_list_semicolon", "=", "partial", "(", "self", ".", "_parse_list", ",", "separator", "=", "';'", ")", "parse_bool", "=", "self", ".", "_parse_bool", "parse_dict", "...
[ 575, 4 ]
[ 601, 9 ]
python
en
['en', 'jv', 'en']
True
ConfigOptionsHandler._parse_packages
(self, value)
Parses `packages` option value. :param value: :rtype: list
Parses `packages` option value.
def _parse_packages(self, value): """Parses `packages` option value. :param value: :rtype: list """ find_directives = ['find:', 'find_namespace:'] trimmed_value = value.strip() if trimmed_value not in find_directives: return self._parse_list(value) ...
[ "def", "_parse_packages", "(", "self", ",", "value", ")", ":", "find_directives", "=", "[", "'find:'", ",", "'find_namespace:'", "]", "trimmed_value", "=", "value", ".", "strip", "(", ")", "if", "trimmed_value", "not", "in", "find_directives", ":", "return", ...
[ 603, 4 ]
[ 629, 43 ]
python
en
['en', 'en', 'en']
True
ConfigOptionsHandler.parse_section_packages__find
(self, section_options)
Parses `packages.find` configuration file section. To be used in conjunction with _parse_packages(). :param dict section_options:
Parses `packages.find` configuration file section.
def parse_section_packages__find(self, section_options): """Parses `packages.find` configuration file section. To be used in conjunction with _parse_packages(). :param dict section_options: """ section_data = self._parse_section_to_dict( section_options, self._parse...
[ "def", "parse_section_packages__find", "(", "self", ",", "section_options", ")", ":", "section_data", "=", "self", ".", "_parse_section_to_dict", "(", "section_options", ",", "self", ".", "_parse_list", ")", "valid_keys", "=", "[", "'where'", ",", "'include'", ","...
[ 631, 4 ]
[ 650, 26 ]
python
en
['en', 'en', 'en']
True
ConfigOptionsHandler.parse_section_entry_points
(self, section_options)
Parses `entry_points` configuration file section. :param dict section_options:
Parses `entry_points` configuration file section.
def parse_section_entry_points(self, section_options): """Parses `entry_points` configuration file section. :param dict section_options: """ parsed = self._parse_section_to_dict(section_options, self._parse_list) self['entry_points'] = parsed
[ "def", "parse_section_entry_points", "(", "self", ",", "section_options", ")", ":", "parsed", "=", "self", ".", "_parse_section_to_dict", "(", "section_options", ",", "self", ".", "_parse_list", ")", "self", "[", "'entry_points'", "]", "=", "parsed" ]
[ 652, 4 ]
[ 658, 37 ]
python
en
['en', 'en', 'en']
True
ConfigOptionsHandler.parse_section_package_data
(self, section_options)
Parses `package_data` configuration file section. :param dict section_options:
Parses `package_data` configuration file section.
def parse_section_package_data(self, section_options): """Parses `package_data` configuration file section. :param dict section_options: """ self['package_data'] = self._parse_package_data(section_options)
[ "def", "parse_section_package_data", "(", "self", ",", "section_options", ")", ":", "self", "[", "'package_data'", "]", "=", "self", ".", "_parse_package_data", "(", "section_options", ")" ]
[ 670, 4 ]
[ 675, 72 ]
python
en
['en', 'en', 'en']
True
ConfigOptionsHandler.parse_section_exclude_package_data
(self, section_options)
Parses `exclude_package_data` configuration file section. :param dict section_options:
Parses `exclude_package_data` configuration file section.
def parse_section_exclude_package_data(self, section_options): """Parses `exclude_package_data` configuration file section. :param dict section_options: """ self['exclude_package_data'] = self._parse_package_data( section_options)
[ "def", "parse_section_exclude_package_data", "(", "self", ",", "section_options", ")", ":", "self", "[", "'exclude_package_data'", "]", "=", "self", ".", "_parse_package_data", "(", "section_options", ")" ]
[ 677, 4 ]
[ 683, 28 ]
python
en
['en', 'en', 'en']
True
ConfigOptionsHandler.parse_section_extras_require
(self, section_options)
Parses `extras_require` configuration file section. :param dict section_options:
Parses `extras_require` configuration file section.
def parse_section_extras_require(self, section_options): """Parses `extras_require` configuration file section. :param dict section_options: """ parse_list = partial(self._parse_list, separator=';') self['extras_require'] = self._parse_section_to_dict( section_option...
[ "def", "parse_section_extras_require", "(", "self", ",", "section_options", ")", ":", "parse_list", "=", "partial", "(", "self", ".", "_parse_list", ",", "separator", "=", "';'", ")", "self", "[", "'extras_require'", "]", "=", "self", ".", "_parse_section_to_dic...
[ 685, 4 ]
[ 692, 40 ]
python
en
['es', 'en', 'en']
True
ConfigOptionsHandler.parse_section_data_files
(self, section_options)
Parses `data_files` configuration file section. :param dict section_options:
Parses `data_files` configuration file section.
def parse_section_data_files(self, section_options): """Parses `data_files` configuration file section. :param dict section_options: """ parsed = self._parse_section_to_dict(section_options, self._parse_list) self['data_files'] = [(k, v) for k, v in parsed.items()]
[ "def", "parse_section_data_files", "(", "self", ",", "section_options", ")", ":", "parsed", "=", "self", ".", "_parse_section_to_dict", "(", "section_options", ",", "self", ".", "_parse_list", ")", "self", "[", "'data_files'", "]", "=", "[", "(", "k", ",", "...
[ 694, 4 ]
[ 700, 64 ]
python
en
['en', 'en', 'en']
True
read_mach_header
(lib_file, seek=None)
This funcition parse mach-O header and extract information about minimal system version :param lib_file: reference to opened library file with pointer
This funcition parse mach-O header and extract information about minimal system version
def read_mach_header(lib_file, seek=None): """ This funcition parse mach-O header and extract information about minimal system version :param lib_file: reference to opened library file with pointer """ if seek is not None: lib_file.seek(seek) base_class, magic_number = get_base_clas...
[ "def", "read_mach_header", "(", "lib_file", ",", "seek", "=", "None", ")", ":", "if", "seek", "is", "not", "None", ":", "lib_file", ".", "seek", "(", "seek", ")", "base_class", ",", "magic_number", "=", "get_base_class_and_magic_number", "(", "lib_file", ")"...
[ 289, 0 ]
[ 333, 20 ]
python
en
['en', 'error', 'th']
False
RequestException.__init__
(self, *args, **kwargs)
Initialize RequestException with `request` and `response` objects.
Initialize RequestException with `request` and `response` objects.
def __init__(self, *args, **kwargs): """Initialize RequestException with `request` and `response` objects.""" response = kwargs.pop('response', None) self.response = response self.request = kwargs.pop('request', None) if (response is not None and not self.request and ...
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "response", "=", "kwargs", ".", "pop", "(", "'response'", ",", "None", ")", "self", ".", "response", "=", "response", "self", ".", "request", "=", "kwargs", ".", "...
[ 16, 4 ]
[ 24, 63 ]
python
en
['en', 'en', 'en']
True
NameAliasMixin.get_real_name
(self)
Returns the real name (object name) of this identifier.
Returns the real name (object name) of this identifier.
def get_real_name(self): """Returns the real name (object name) of this identifier.""" # a.b dot_idx, _ = self.token_next_by(m=(T.Punctuation, '.')) return self._get_first_name(dot_idx, real_name=True)
[ "def", "get_real_name", "(", "self", ")", ":", "# a.b", "dot_idx", ",", "_", "=", "self", ".", "token_next_by", "(", "m", "=", "(", "T", ".", "Punctuation", ",", "'.'", ")", ")", "return", "self", ".", "_get_first_name", "(", "dot_idx", ",", "real_name...
[ 21, 4 ]
[ 25, 60 ]
python
en
['en', 'en', 'en']
True
NameAliasMixin.get_alias
(self)
Returns the alias for this identifier or ``None``.
Returns the alias for this identifier or ``None``.
def get_alias(self): """Returns the alias for this identifier or ``None``.""" # "name AS alias" kw_idx, kw = self.token_next_by(m=(T.Keyword, 'AS')) if kw is not None: return self._get_first_name(kw_idx + 1, keywords=True) # "name alias" or "complicated column expre...
[ "def", "get_alias", "(", "self", ")", ":", "# \"name AS alias\"", "kw_idx", ",", "kw", "=", "self", ".", "token_next_by", "(", "m", "=", "(", "T", ".", "Keyword", ",", "'AS'", ")", ")", "if", "kw", "is", "not", "None", ":", "return", "self", ".", "...
[ 27, 4 ]
[ 38, 53 ]
python
en
['en', 'en', 'en']
True
Statement.get_type
(self)
Returns the type of a statement. The returned value is a string holding an upper-cased reprint of the first DML or DDL keyword. If the first token in this group isn't a DML or DDL keyword "UNKNOWN" is returned. Whitespaces and comments at the beginning of the statement are igno...
Returns the type of a statement.
def get_type(self): """Returns the type of a statement. The returned value is a string holding an upper-cased reprint of the first DML or DDL keyword. If the first token in this group isn't a DML or DDL keyword "UNKNOWN" is returned. Whitespaces and comments at the beginning of...
[ "def", "get_type", "(", "self", ")", ":", "first_token", "=", "self", ".", "token_first", "(", "skip_cm", "=", "True", ")", "if", "first_token", "is", "None", ":", "# An \"empty\" statement that either has not tokens at all", "# or only whitespace tokens.", "return", ...
[ 411, 4 ]
[ 444, 24 ]
python
en
['en', 'en', 'en']
True
Identifier.is_wildcard
(self)
Return ``True`` if this identifier contains a wildcard.
Return ``True`` if this identifier contains a wildcard.
def is_wildcard(self): """Return ``True`` if this identifier contains a wildcard.""" _, token = self.token_next_by(t=T.Wildcard) return token is not None
[ "def", "is_wildcard", "(", "self", ")", ":", "_", ",", "token", "=", "self", ".", "token_next_by", "(", "t", "=", "T", ".", "Wildcard", ")", "return", "token", "is", "not", "None" ]
[ 453, 4 ]
[ 456, 32 ]
python
en
['en', 'en', 'en']
True
Identifier.get_typecast
(self)
Returns the typecast or ``None`` of this object as a string.
Returns the typecast or ``None`` of this object as a string.
def get_typecast(self): """Returns the typecast or ``None`` of this object as a string.""" midx, marker = self.token_next_by(m=(T.Punctuation, '::')) nidx, next_ = self.token_next(midx, skip_ws=False) return next_.value if next_ else None
[ "def", "get_typecast", "(", "self", ")", ":", "midx", ",", "marker", "=", "self", ".", "token_next_by", "(", "m", "=", "(", "T", ".", "Punctuation", ",", "'::'", ")", ")", "nidx", ",", "next_", "=", "self", ".", "token_next", "(", "midx", ",", "ski...
[ 458, 4 ]
[ 462, 45 ]
python
en
['en', 'en', 'en']
True
Identifier.get_ordering
(self)
Returns the ordering or ``None`` as uppercase string.
Returns the ordering or ``None`` as uppercase string.
def get_ordering(self): """Returns the ordering or ``None`` as uppercase string.""" _, ordering = self.token_next_by(t=T.Keyword.Order) return ordering.normalized if ordering else None
[ "def", "get_ordering", "(", "self", ")", ":", "_", ",", "ordering", "=", "self", ".", "token_next_by", "(", "t", "=", "T", ".", "Keyword", ".", "Order", ")", "return", "ordering", ".", "normalized", "if", "ordering", "else", "None" ]
[ 464, 4 ]
[ 467, 56 ]
python
en
['en', 'en', 'en']
True
Identifier.get_array_indices
(self)
Returns an iterator of index token lists
Returns an iterator of index token lists
def get_array_indices(self): """Returns an iterator of index token lists""" for token in self.tokens: if isinstance(token, SquareBrackets): # Use [1:-1] index to discard the square brackets yield token.tokens[1:-1]
[ "def", "get_array_indices", "(", "self", ")", ":", "for", "token", "in", "self", ".", "tokens", ":", "if", "isinstance", "(", "token", ",", "SquareBrackets", ")", ":", "# Use [1:-1] index to discard the square brackets", "yield", "token", ".", "tokens", "[", "1"...
[ 469, 4 ]
[ 475, 40 ]
python
en
['en', 'en', 'en']
True
IdentifierList.get_identifiers
(self)
Returns the identifiers. Whitespaces and punctuations are not included in this generator.
Returns the identifiers.
def get_identifiers(self): """Returns the identifiers. Whitespaces and punctuations are not included in this generator. """ for token in self.tokens: if not (token.is_whitespace or token.match(T.Punctuation, ',')): yield token
[ "def", "get_identifiers", "(", "self", ")", ":", "for", "token", "in", "self", ".", "tokens", ":", "if", "not", "(", "token", ".", "is_whitespace", "or", "token", ".", "match", "(", "T", ".", "Punctuation", ",", "','", ")", ")", ":", "yield", "token"...
[ 481, 4 ]
[ 488, 27 ]
python
en
['en', 'nl', 'en']
True
Case.get_cases
(self, skip_ws=False)
Returns a list of 2-tuples (condition, value). If an ELSE exists condition is None.
Returns a list of 2-tuples (condition, value).
def get_cases(self, skip_ws=False): """Returns a list of 2-tuples (condition, value). If an ELSE exists condition is None. """ CONDITION = 1 VALUE = 2 ret = [] mode = CONDITION for token in self.tokens: # Set mode from the current statement ...
[ "def", "get_cases", "(", "self", ",", "skip_ws", "=", "False", ")", ":", "CONDITION", "=", "1", "VALUE", "=", "2", "ret", "=", "[", "]", "mode", "=", "CONDITION", "for", "token", "in", "self", ".", "tokens", ":", "# Set mode from the current statement", ...
[ 572, 4 ]
[ 617, 18 ]
python
en
['en', 'en', 'en']
True
Function.get_parameters
(self)
Return a list of parameters.
Return a list of parameters.
def get_parameters(self): """Return a list of parameters.""" parenthesis = self.tokens[-1] for token in parenthesis.tokens: if isinstance(token, IdentifierList): return token.get_identifiers() elif imt(token, i=(Function, Identifier), t=T.Literal): ...
[ "def", "get_parameters", "(", "self", ")", ":", "parenthesis", "=", "self", ".", "tokens", "[", "-", "1", "]", "for", "token", "in", "parenthesis", ".", "tokens", ":", "if", "isinstance", "(", "token", ",", "IdentifierList", ")", ":", "return", "token", ...
[ 623, 4 ]
[ 631, 17 ]
python
en
['en', 'en', 'en']
True
HumanizeTests.test_i18n_html_ordinal
(self)
Allow html in output on i18n strings
Allow html in output on i18n strings
def test_i18n_html_ordinal(self): """Allow html in output on i18n strings""" test_list = ('1', '2', '3', '4', '11', '12', '13', '101', '102', '103', '111', 'something else', None) result_list = ('1<sup>er</sup>', '2<sup>e</sup>', '3<sup>e</sup>', '4<sup>...
[ "def", "test_i18n_html_ordinal", "(", "self", ")", ":", "test_list", "=", "(", "'1'", ",", "'2'", ",", "'3'", ",", "'4'", ",", "'11'", ",", "'12'", ",", "'13'", ",", "'101'", ",", "'102'", ",", "'103'", ",", "'111'", ",", "'something else'", ",", "No...
[ 56, 4 ]
[ 67, 80 ]
python
en
['en', 'en', 'en']
True
HumanizeTests.test_naturaltime_as_documented
(self)
#23340 -- Verify the documented behavior of humanize.naturaltime.
#23340 -- Verify the documented behavior of humanize.naturaltime.
def test_naturaltime_as_documented(self): """ #23340 -- Verify the documented behavior of humanize.naturaltime. """ time_format = '%d %b %Y %H:%M:%S' documented_now = datetime.datetime.strptime('17 Feb 2007 16:30:00', time_format) test_data = ( ('17 Feb 2007 ...
[ "def", "test_naturaltime_as_documented", "(", "self", ")", ":", "time_format", "=", "'%d %b %Y %H:%M:%S'", "documented_now", "=", "datetime", ".", "datetime", ".", "strptime", "(", "'17 Feb 2007 16:30:00'", ",", "time_format", ")", "test_data", "=", "(", "(", "'17 F...
[ 242, 4 ]
[ 287, 54 ]
python
en
['en', 'error', 'th']
False
test_disallowed_methods
(all_user_types_api_client, list_url, detail_url)
Tests that only safe methods are allowed to unit list and detail endpoints.
Tests that only safe methods are allowed to unit list and detail endpoints.
def test_disallowed_methods(all_user_types_api_client, list_url, detail_url): """ Tests that only safe methods are allowed to unit list and detail endpoints. """ check_only_safe_methods_allowed(all_user_types_api_client, (list_url, detail_url))
[ "def", "test_disallowed_methods", "(", "all_user_types_api_client", ",", "list_url", ",", "detail_url", ")", ":", "check_only_safe_methods_allowed", "(", "all_user_types_api_client", ",", "(", "list_url", ",", "detail_url", ")", ")" ]
[ 24, 0 ]
[ 28, 86 ]
python
en
['en', 'error', 'th']
False
test_query_counts
(user_api_client, staff_api_client, list_url, django_assert_max_num_queries)
Test that DB query count is less than allowed
Test that DB query count is less than allowed
def test_query_counts(user_api_client, staff_api_client, list_url, django_assert_max_num_queries): """ Test that DB query count is less than allowed """ with django_assert_max_num_queries(MAX_QUERIES): user_api_client.get(list_url) with django_assert_max_num_queries(MAX_QUERIES): st...
[ "def", "test_query_counts", "(", "user_api_client", ",", "staff_api_client", ",", "list_url", ",", "django_assert_max_num_queries", ")", ":", "with", "django_assert_max_num_queries", "(", "MAX_QUERIES", ")", ":", "user_api_client", ".", "get", "(", "list_url", ")", "w...
[ 100, 0 ]
[ 108, 38 ]
python
en
['en', 'error', 'th']
False
create_streams_if_needed
( realm: Realm, stream_dicts: List[StreamDict], acting_user: Optional[UserProfile] = None )
Note that stream_dict["name"] is assumed to already be stripped of whitespace
Note that stream_dict["name"] is assumed to already be stripped of whitespace
def create_streams_if_needed( realm: Realm, stream_dicts: List[StreamDict], acting_user: Optional[UserProfile] = None ) -> Tuple[List[Stream], List[Stream]]: """Note that stream_dict["name"] is assumed to already be stripped of whitespace""" added_streams: List[Stream] = [] existing_streams: List[St...
[ "def", "create_streams_if_needed", "(", "realm", ":", "Realm", ",", "stream_dicts", ":", "List", "[", "StreamDict", "]", ",", "acting_user", ":", "Optional", "[", "UserProfile", "]", "=", "None", ")", "->", "Tuple", "[", "List", "[", "Stream", "]", ",", ...
[ 140, 0 ]
[ 166, 42 ]
python
en
['en', 'en', 'en']
True
access_stream_common
( user_profile: UserProfile, stream: Stream, error: str, require_active: bool = True, allow_realm_admin: bool = False, )
Common function for backend code where the target use attempts to access the target stream, returning all the data fetched along the way. If that user does not have permission to access that stream, we throw an exception. A design goal is that the error message is the same for streams you can't access...
Common function for backend code where the target use attempts to access the target stream, returning all the data fetched along the way. If that user does not have permission to access that stream, we throw an exception. A design goal is that the error message is the same for streams you can't access...
def access_stream_common( user_profile: UserProfile, stream: Stream, error: str, require_active: bool = True, allow_realm_admin: bool = False, ) -> Optional[Subscription]: """Common function for backend code where the target use attempts to access the target stream, returning all the data fe...
[ "def", "access_stream_common", "(", "user_profile", ":", "UserProfile", ",", "stream", ":", "Stream", ",", "error", ":", "str", ",", "require_active", ":", "bool", "=", "True", ",", "allow_realm_admin", ":", "bool", "=", "False", ",", ")", "->", "Optional", ...
[ 310, 0 ]
[ 355, 30 ]
python
en
['en', 'en', 'en']
True
access_stream_for_unmute_topic_by_name
( user_profile: UserProfile, stream_name: str, error: str )
It may seem a little silly to have this helper function for unmuting topics, but it gets around a linter warning, and it helps to be able to review all security-related stuff in one place. Our policy for accessing streams when you unmute a topic is that you don't necessarily need to have an active...
It may seem a little silly to have this helper function for unmuting topics, but it gets around a linter warning, and it helps to be able to review all security-related stuff in one place.
def access_stream_for_unmute_topic_by_name( user_profile: UserProfile, stream_name: str, error: str ) -> Stream: """ It may seem a little silly to have this helper function for unmuting topics, but it gets around a linter warning, and it helps to be able to review all security-related stuff in one p...
[ "def", "access_stream_for_unmute_topic_by_name", "(", "user_profile", ":", "UserProfile", ",", "stream_name", ":", "str", ",", "error", ":", "str", ")", "->", "Stream", ":", "try", ":", "stream", "=", "get_stream", "(", "stream_name", ",", "user_profile", ".", ...
[ 442, 0 ]
[ 462, 17 ]
python
en
['en', 'error', 'th']
False
can_access_stream_history
(user_profile: UserProfile, stream: Stream)
Determine whether the provided user is allowed to access the history of the target stream. The stream is specified by name. This is used by the caller to determine whether this user can get historical messages before they joined for a narrowing search. Because of the way our search is currently struc...
Determine whether the provided user is allowed to access the history of the target stream. The stream is specified by name.
def can_access_stream_history(user_profile: UserProfile, stream: Stream) -> bool: """Determine whether the provided user is allowed to access the history of the target stream. The stream is specified by name. This is used by the caller to determine whether this user can get historical messages before ...
[ "def", "can_access_stream_history", "(", "user_profile", ":", "UserProfile", ",", "stream", ":", "Stream", ")", "->", "bool", ":", "if", "stream", ".", "is_web_public", ":", "return", "True", "if", "stream", ".", "is_history_realm_public", "(", ")", "and", "no...
[ 475, 0 ]
[ 505, 16 ]
python
en
['en', 'en', 'en']
True
list_to_streams
( streams_raw: Iterable[StreamDict], user_profile: UserProfile, autocreate: bool = False, admin_access_required: bool = False, )
Converts list of dicts to a list of Streams, validating input in the process For each stream name, we validate it to ensure it meets our requirements for a proper stream name using check_stream_name. This function in autocreate mode should be atomic: either an exception will be raised during a prechec...
Converts list of dicts to a list of Streams, validating input in the process
def list_to_streams( streams_raw: Iterable[StreamDict], user_profile: UserProfile, autocreate: bool = False, admin_access_required: bool = False, ) -> Tuple[List[Stream], List[Stream]]: """Converts list of dicts to a list of Streams, validating input in the process For each stream name, we vali...
[ "def", "list_to_streams", "(", "streams_raw", ":", "Iterable", "[", "StreamDict", "]", ",", "user_profile", ":", "UserProfile", ",", "autocreate", ":", "bool", "=", "False", ",", "admin_access_required", ":", "bool", "=", "False", ",", ")", "->", "Tuple", "[...
[ 558, 0 ]
[ 643, 44 ]
python
en
['en', 'en', 'en']
True
get_stream_by_narrow_operand_access_unchecked
(operand: Union[str, int], realm: Realm)
This is required over access_stream_* in certain cases where we need the stream data only to prepare a response that user can access and not send it out to unauthorized recipients.
This is required over access_stream_* in certain cases where we need the stream data only to prepare a response that user can access and not send it out to unauthorized recipients.
def get_stream_by_narrow_operand_access_unchecked(operand: Union[str, int], realm: Realm) -> Stream: """This is required over access_stream_* in certain cases where we need the stream data only to prepare a response that user can access and not send it out to unauthorized recipients. """ if isinstan...
[ "def", "get_stream_by_narrow_operand_access_unchecked", "(", "operand", ":", "Union", "[", "str", ",", "int", "]", ",", "realm", ":", "Realm", ")", "->", "Stream", ":", "if", "isinstance", "(", "operand", ",", "str", ")", ":", "return", "get_stream", "(", ...
[ 653, 0 ]
[ 660, 52 ]
python
en
['en', 'en', 'en']
True
ListFilter.has_output
(self)
Return True if some choices would be output for this filter.
Return True if some choices would be output for this filter.
def has_output(self): """ Return True if some choices would be output for this filter. """ raise NotImplementedError('subclasses of ListFilter must provide a has_output() method')
[ "def", "has_output", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of ListFilter must provide a has_output() method'", ")" ]
[ 33, 4 ]
[ 37, 96 ]
python
en
['en', 'error', 'th']
False
ListFilter.choices
(self, changelist)
Return choices ready to be output in the template. `changelist` is the ChangeList to be displayed.
Return choices ready to be output in the template.
def choices(self, changelist): """ Return choices ready to be output in the template. `changelist` is the ChangeList to be displayed. """ raise NotImplementedError('subclasses of ListFilter must provide a choices() method')
[ "def", "choices", "(", "self", ",", "changelist", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of ListFilter must provide a choices() method'", ")" ]
[ 39, 4 ]
[ 45, 93 ]
python
en
['en', 'error', 'th']
False
ListFilter.queryset
(self, request, queryset)
Return the filtered queryset.
Return the filtered queryset.
def queryset(self, request, queryset): """ Return the filtered queryset. """ raise NotImplementedError('subclasses of ListFilter must provide a queryset() method')
[ "def", "queryset", "(", "self", ",", "request", ",", "queryset", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of ListFilter must provide a queryset() method'", ")" ]
[ 47, 4 ]
[ 51, 94 ]
python
en
['en', 'error', 'th']
False
ListFilter.expected_parameters
(self)
Return the list of parameter names that are expected from the request's query string and that will be used by this filter.
Return the list of parameter names that are expected from the request's query string and that will be used by this filter.
def expected_parameters(self): """ Return the list of parameter names that are expected from the request's query string and that will be used by this filter. """ raise NotImplementedError('subclasses of ListFilter must provide an expected_parameters() method')
[ "def", "expected_parameters", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of ListFilter must provide an expected_parameters() method'", ")" ]
[ 53, 4 ]
[ 58, 106 ]
python
en
['en', 'error', 'th']
False
SimpleListFilter.value
(self)
Return the value (in string format) provided in the request's query string for this filter, if any, or None if the value wasn't provided.
Return the value (in string format) provided in the request's query string for this filter, if any, or None if the value wasn't provided.
def value(self): """ Return the value (in string format) provided in the request's query string for this filter, if any, or None if the value wasn't provided. """ return self.used_parameters.get(self.parameter_name)
[ "def", "value", "(", "self", ")", ":", "return", "self", ".", "used_parameters", ".", "get", "(", "self", ".", "parameter_name", ")" ]
[ 83, 4 ]
[ 89, 60 ]
python
en
['en', 'error', 'th']
False
SimpleListFilter.lookups
(self, request, model_admin)
Must be overridden to return a list of tuples (value, verbose value)
Must be overridden to return a list of tuples (value, verbose value)
def lookups(self, request, model_admin): """ Must be overridden to return a list of tuples (value, verbose value) """ raise NotImplementedError( 'The SimpleListFilter.lookups() method must be overridden to ' 'return a list of tuples (value, verbose value).' ...
[ "def", "lookups", "(", "self", ",", "request", ",", "model_admin", ")", ":", "raise", "NotImplementedError", "(", "'The SimpleListFilter.lookups() method must be overridden to '", "'return a list of tuples (value, verbose value).'", ")" ]
[ 91, 4 ]
[ 98, 9 ]
python
en
['en', 'error', 'th']
False
RelatedFieldListFilter.include_empty_choice
(self)
Return True if a "(None)" choice should be included, which filters out everything except empty relationships.
Return True if a "(None)" choice should be included, which filters out everything except empty relationships.
def include_empty_choice(self): """ Return True if a "(None)" choice should be included, which filters out everything except empty relationships. """ return self.field.null or (self.field.is_relation and self.field.many_to_many)
[ "def", "include_empty_choice", "(", "self", ")", ":", "return", "self", ".", "field", ".", "null", "or", "(", "self", ".", "field", ".", "is_relation", "and", "self", ".", "field", ".", "many_to_many", ")" ]
[ 178, 4 ]
[ 183, 86 ]
python
en
['en', 'error', 'th']
False
RelatedFieldListFilter.field_admin_ordering
(self, field, request, model_admin)
Return the model admin's ordering for related field, if provided.
Return the model admin's ordering for related field, if provided.
def field_admin_ordering(self, field, request, model_admin): """ Return the model admin's ordering for related field, if provided. """ related_admin = model_admin.admin_site._registry.get(field.remote_field.model) if related_admin is not None: return related_admin.get...
[ "def", "field_admin_ordering", "(", "self", ",", "field", ",", "request", ",", "model_admin", ")", ":", "related_admin", "=", "model_admin", ".", "admin_site", ".", "_registry", ".", "get", "(", "field", ".", "remote_field", ".", "model", ")", "if", "related...
[ 195, 4 ]
[ 202, 17 ]
python
en
['en', 'error', 'th']
False
colorize
(text='', opts=(), **kwargs)
Returns your text, enclosed in ANSI graphics codes. Depends on the keyword arguments 'fg' and 'bg', and the contents of the opts tuple/list. Returns the RESET code if no parameters are given. Valid colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' Valid o...
Returns your text, enclosed in ANSI graphics codes.
def colorize(text='', opts=(), **kwargs): """ Returns your text, enclosed in ANSI graphics codes. Depends on the keyword arguments 'fg' and 'bg', and the contents of the opts tuple/list. Returns the RESET code if no parameters are given. Valid colors: 'black', 'red', 'green', 'yellow'...
[ "def", "colorize", "(", "text", "=", "''", ",", "opts", "=", "(", ")", ",", "*", "*", "kwargs", ")", ":", "code_list", "=", "[", "]", "if", "text", "==", "''", "and", "len", "(", "opts", ")", "==", "1", "and", "opts", "[", "0", "]", "==", "...
[ 14, 0 ]
[ 56, 68 ]
python
en
['en', 'error', 'th']
False
make_style
(opts=(), **kwargs)
Returns a function with default parameters for colorize() Example: bold_red = make_style(opts=('bold',), fg='red') print(bold_red('hello')) KEYWORD = make_style(fg='yellow') COMMENT = make_style(fg='blue', opts=('bold',))
Returns a function with default parameters for colorize()
def make_style(opts=(), **kwargs): """ Returns a function with default parameters for colorize() Example: bold_red = make_style(opts=('bold',), fg='red') print(bold_red('hello')) KEYWORD = make_style(fg='yellow') COMMENT = make_style(fg='blue', opts=('bold',)) """ re...
[ "def", "make_style", "(", "opts", "=", "(", ")", ",", "*", "*", "kwargs", ")", ":", "return", "lambda", "text", ":", "colorize", "(", "text", ",", "opts", ",", "*", "*", "kwargs", ")" ]
[ 59, 0 ]
[ 69, 54 ]
python
en
['en', 'error', 'th']
False
parse_color_setting
(config_string)
Parse a DJANGO_COLORS environment variable to produce the system palette The general form of a pallete definition is: "palette;role=fg;role=fg/bg;role=fg,option,option;role=fg/bg,option,option" where: palette is a named palette; one of 'light', 'dark', or 'nocolor'. role is a named st...
Parse a DJANGO_COLORS environment variable to produce the system palette
def parse_color_setting(config_string): """Parse a DJANGO_COLORS environment variable to produce the system palette The general form of a pallete definition is: "palette;role=fg;role=fg/bg;role=fg,option,option;role=fg/bg,option,option" where: palette is a named palette; one of 'light', '...
[ "def", "parse_color_setting", "(", "config_string", ")", ":", "if", "not", "config_string", ":", "return", "PALETTES", "[", "DEFAULT_PALETTE", "]", "# Split the color configuration into parts", "parts", "=", "config_string", ".", "lower", "(", ")", ".", "split", "("...
[ 140, 0 ]
[ 217, 18 ]
python
en
['en', 'en', 'en']
True
test_histnorm
(shape)
Test this to guard against an implementation change.
Test this to guard against an implementation change.
def test_histnorm(shape): """Test this to guard against an implementation change.""" sample = create_input(shape) transform = cpt.Compose([tvt.ToTensor(), cpt.HistogramNormalize()]) image = np.transpose( torch.tensor(np.array(sample["image"]), dtype=torch.float).numpy(), (2, 0, 1) ) # g...
[ "def", "test_histnorm", "(", "shape", ")", ":", "sample", "=", "create_input", "(", "shape", ")", "transform", "=", "cpt", ".", "Compose", "(", "[", "tvt", ".", "ToTensor", "(", ")", ",", "cpt", ".", "HistogramNormalize", "(", ")", "]", ")", "image", ...
[ 56, 0 ]
[ 79, 49 ]
python
en
['en', 'en', 'en']
True
test_rand_gauss_blur
(shape)
Test this to guard against an implementation change.
Test this to guard against an implementation change.
def test_rand_gauss_blur(shape): """Test this to guard against an implementation change.""" seed = 123 sample = create_input(shape) transform = cpt.Compose([tvt.ToTensor(), cpt.RandomGaussianBlur(p=1)]) # run the custom blur np.random.seed(seed) image = tvt.functional.to_tensor(sample["ima...
[ "def", "test_rand_gauss_blur", "(", "shape", ")", ":", "seed", "=", "123", "sample", "=", "create_input", "(", "shape", ")", "transform", "=", "cpt", ".", "Compose", "(", "[", "tvt", ".", "ToTensor", "(", ")", ",", "cpt", ".", "RandomGaussianBlur", "(", ...
[ 83, 0 ]
[ 117, 49 ]
python
en
['en', 'en', 'en']
True
test_add_noise
(shape)
Test this to guard against an implementation change.
Test this to guard against an implementation change.
def test_add_noise(shape): """Test this to guard against an implementation change.""" seed = 456 sample = create_input(shape) transform = cpt.Compose([tvt.ToTensor(), cpt.AddGaussianNoise(p=1)]) # run the custom noise np.random.seed(seed) image = tvt.functional.to_tensor(sample["image"]) *...
[ "def", "test_add_noise", "(", "shape", ")", ":", "seed", "=", "456", "sample", "=", "create_input", "(", "shape", ")", "transform", "=", "cpt", ".", "Compose", "(", "[", "tvt", ".", "ToTensor", "(", ")", ",", "cpt", ".", "AddGaussianNoise", "(", "p", ...
[ 121, 0 ]
[ 158, 49 ]
python
en
['en', 'en', 'en']
True
Loss.__init__
(self, model, hparams=None, attack=None)
:param model: Model instance, the model on which to apply the loss. :param hparams: dict, hyper-parameters for the loss. :param attack: cleverhans.attacks.Attack instance
:param model: Model instance, the model on which to apply the loss. :param hparams: dict, hyper-parameters for the loss. :param attack: cleverhans.attacks.Attack instance
def __init__(self, model, hparams=None, attack=None): """ :param model: Model instance, the model on which to apply the loss. :param hparams: dict, hyper-parameters for the loss. :param attack: cleverhans.attacks.Attack instance """ assert isinstance(model, Model) ...
[ "def", "__init__", "(", "self", ",", "model", ",", "hparams", "=", "None", ",", "attack", "=", "None", ")", ":", "assert", "isinstance", "(", "model", ",", "Model", ")", "standard", "=", "attack", "is", "None", "or", "isinstance", "(", "attack", ",", ...
[ 29, 4 ]
[ 66, 28 ]
python
en
['en', 'error', 'th']
False
Loss.save
(self, path)
Save loss in json format
Save loss in json format
def save(self, path): """Save loss in json format""" json.dump( dict(loss=self.__class__.__name__, params=self.hparams), open(os.path.join(path, "loss.json"), "wb"), )
[ "def", "save", "(", "self", ",", "path", ")", ":", "json", ".", "dump", "(", "dict", "(", "loss", "=", "self", ".", "__class__", ".", "__name__", ",", "params", "=", "self", ".", "hparams", ")", ",", "open", "(", "os", ".", "path", ".", "join", ...
[ 68, 4 ]
[ 73, 9 ]
python
en
['en', 'en', 'it']
True
Loss.fprop
(self, x, y)
Forward propagate the loss. Loss should be a scalar value, independent of batch size (i.e. use reduce_mean over batch axis, don't use reduce_sum or return a tensor). Scalar losses are easier to add together, e.g. through `WeightedSum`. Mean losses are easier to redistribute across multip...
Forward propagate the loss. Loss should be a scalar value, independent of batch size (i.e. use reduce_mean over batch axis, don't use reduce_sum or return a tensor). Scalar losses are easier to add together, e.g. through `WeightedSum`. Mean losses are easier to redistribute across multip...
def fprop(self, x, y): """Forward propagate the loss. Loss should be a scalar value, independent of batch size (i.e. use reduce_mean over batch axis, don't use reduce_sum or return a tensor). Scalar losses are easier to add together, e.g. through `WeightedSum`. Mean losses are ea...
[ "def", "fprop", "(", "self", ",", "x", ",", "y", ")", ":", "raise", "NotImplementedError" ]
[ 75, 4 ]
[ 85, 33 ]
python
en
['en', 'it', 'en']
True
LossCrossEntropy.__init__
(self, model, smoothing=0.0, attack=None, **kwargs)
Constructor. :param model: Model instance, the model on which to apply the loss. :param smoothing: float, amount of label smoothing for cross-entropy. :param attack: function, given an input x, return an attacked x'.
Constructor. :param model: Model instance, the model on which to apply the loss. :param smoothing: float, amount of label smoothing for cross-entropy. :param attack: function, given an input x, return an attacked x'.
def __init__(self, model, smoothing=0.0, attack=None, **kwargs): """Constructor. :param model: Model instance, the model on which to apply the loss. :param smoothing: float, amount of label smoothing for cross-entropy. :param attack: function, given an input x, return an attacked x'. ...
[ "def", "__init__", "(", "self", ",", "model", ",", "smoothing", "=", "0.0", ",", "attack", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "smoothing", "<", "0", "or", "smoothing", ">", "1", ":", "raise", "ValueError", "(", "\"Smoothing must be i...
[ 263, 4 ]
[ 273, 34 ]
python
en
['en', 'en', 'en']
False
LossFeaturePairing.__init__
(self, model, weight, attack, **kwargs)
Constructor. :param model: Model instance, the model on which to apply the loss. :param weight: float, with of logic pairing loss. :param attack: function, given an input x, return an attacked x'.
Constructor. :param model: Model instance, the model on which to apply the loss. :param weight: float, with of logic pairing loss. :param attack: function, given an input x, return an attacked x'.
def __init__(self, model, weight, attack, **kwargs): """Constructor. :param model: Model instance, the model on which to apply the loss. :param weight: float, with of logic pairing loss. :param attack: function, given an input x, return an attacked x'. """ del kwargs ...
[ "def", "__init__", "(", "self", ",", "model", ",", "weight", ",", "attack", ",", "*", "*", "kwargs", ")", ":", "del", "kwargs", "Loss", ".", "__init__", "(", "self", ",", "model", ",", "locals", "(", ")", ",", "attack", ")", "self", ".", "weight", ...
[ 304, 4 ]
[ 312, 28 ]
python
en
['en', 'en', 'en']
False
LossMixUp.__init__
(self, model, beta, **kwargs)
Constructor. :param model: Model instance, the model on which to apply the loss. :param beta: float, beta distribution parameter for MixUp.
Constructor. :param model: Model instance, the model on which to apply the loss. :param beta: float, beta distribution parameter for MixUp.
def __init__(self, model, beta, **kwargs): """Constructor. :param model: Model instance, the model on which to apply the loss. :param beta: float, beta distribution parameter for MixUp. """ del kwargs Loss.__init__(self, model, locals()) self.beta = beta
[ "def", "__init__", "(", "self", ",", "model", ",", "beta", ",", "*", "*", "kwargs", ")", ":", "del", "kwargs", "Loss", ".", "__init__", "(", "self", ",", "model", ",", "locals", "(", ")", ")", "self", ".", "beta", "=", "beta" ]
[ 337, 4 ]
[ 344, 24 ]
python
en
['en', 'en', 'en']
False
SNNLCrossEntropy.__init__
( self, model, temperature=100.0, layer_names=None, factor=-10.0, optimize_temperature=True, cos_distance=False, )
Constructor. :param model: Model instance, the model on which to apply the loss. :param temperature: Temperature used for SNNL. :layer_names: The names of the layers at which to calculate SNNL. If not provided, then SNNL is applied to each internal layer. :factor: T...
Constructor. :param model: Model instance, the model on which to apply the loss. :param temperature: Temperature used for SNNL. :layer_names: The names of the layers at which to calculate SNNL. If not provided, then SNNL is applied to each internal layer. :factor: T...
def __init__( self, model, temperature=100.0, layer_names=None, factor=-10.0, optimize_temperature=True, cos_distance=False, ): """Constructor. :param model: Model instance, the model on which to apply the loss. :param temperature: Temp...
[ "def", "__init__", "(", "self", ",", "model", ",", "temperature", "=", "100.0", ",", "layer_names", "=", "None", ",", "factor", "=", "-", "10.0", ",", "optimize_temperature", "=", "True", ",", "cos_distance", "=", "False", ",", ")", ":", "CrossEntropy", ...
[ 370, 4 ]
[ 398, 59 ]
python
en
['en', 'en', 'en']
False
SNNLCrossEntropy.pairwise_euclid_distance
(A, B)
Pairwise Euclidean distance between two matrices. :param A: a matrix. :param B: a matrix. :returns: A tensor for the pairwise Euclidean between A and B.
Pairwise Euclidean distance between two matrices. :param A: a matrix. :param B: a matrix.
def pairwise_euclid_distance(A, B): """Pairwise Euclidean distance between two matrices. :param A: a matrix. :param B: a matrix. :returns: A tensor for the pairwise Euclidean between A and B. """ batchA = tf.shape(A)[0] batchB = tf.shape(B)[0] sqr_norm_A...
[ "def", "pairwise_euclid_distance", "(", "A", ",", "B", ")", ":", "batchA", "=", "tf", ".", "shape", "(", "A", ")", "[", "0", "]", "batchB", "=", "tf", ".", "shape", "(", "B", ")", "[", "0", "]", "sqr_norm_A", "=", "tf", ".", "reshape", "(", "tf...
[ 401, 4 ]
[ 417, 47 ]
python
en
['nl', 'en', 'en']
True
SNNLCrossEntropy.pairwise_cos_distance
(A, B)
Pairwise cosine distance between two matrices. :param A: a matrix. :param B: a matrix. :returns: A tensor for the pairwise cosine between A and B.
Pairwise cosine distance between two matrices. :param A: a matrix. :param B: a matrix.
def pairwise_cos_distance(A, B): """Pairwise cosine distance between two matrices. :param A: a matrix. :param B: a matrix. :returns: A tensor for the pairwise cosine between A and B. """ normalized_A = tf.nn.l2_normalize(A, dim=1) normalized_B = tf.nn.l2_normaliz...
[ "def", "pairwise_cos_distance", "(", "A", ",", "B", ")", ":", "normalized_A", "=", "tf", ".", "nn", ".", "l2_normalize", "(", "A", ",", "dim", "=", "1", ")", "normalized_B", "=", "tf", ".", "nn", ".", "l2_normalize", "(", "B", ",", "dim", "=", "1",...
[ 420, 4 ]
[ 430, 23 ]
python
en
['en', 'en', 'en']
True
SNNLCrossEntropy.fits
(A, B, temp, cos_distance)
Exponentiated pairwise distance between each element of A and all those of B. :param A: a matrix. :param B: a matrix. :param temp: Temperature :cos_distance: Boolean for using cosine or Euclidean distance. :returns: A tensor for the exponentiated pairwise distance betwee...
Exponentiated pairwise distance between each element of A and all those of B. :param A: a matrix. :param B: a matrix. :param temp: Temperature :cos_distance: Boolean for using cosine or Euclidean distance.
def fits(A, B, temp, cos_distance): """Exponentiated pairwise distance between each element of A and all those of B. :param A: a matrix. :param B: a matrix. :param temp: Temperature :cos_distance: Boolean for using cosine or Euclidean distance. :returns: A tensor...
[ "def", "fits", "(", "A", ",", "B", ",", "temp", ",", "cos_distance", ")", ":", "if", "cos_distance", ":", "distance_matrix", "=", "SNNLCrossEntropy", ".", "pairwise_cos_distance", "(", "A", ",", "B", ")", "else", ":", "distance_matrix", "=", "SNNLCrossEntrop...
[ 433, 4 ]
[ 448, 48 ]
python
en
['en', 'en', 'en']
True
SNNLCrossEntropy.pick_probability
(x, temp, cos_distance)
Row normalized exponentiated pairwise distance between all the elements of x. Conceptualized as the probability of sampling a neighbor point for every element of x, proportional to the distance between the points. :param x: a matrix :param temp: Temperature :cos_distance: Boolean...
Row normalized exponentiated pairwise distance between all the elements of x. Conceptualized as the probability of sampling a neighbor point for every element of x, proportional to the distance between the points. :param x: a matrix :param temp: Temperature :cos_distance: Boolean...
def pick_probability(x, temp, cos_distance): """Row normalized exponentiated pairwise distance between all the elements of x. Conceptualized as the probability of sampling a neighbor point for every element of x, proportional to the distance between the points. :param x: a matrix ...
[ "def", "pick_probability", "(", "x", ",", "temp", ",", "cos_distance", ")", ":", "f", "=", "SNNLCrossEntropy", ".", "fits", "(", "x", ",", "x", ",", "temp", ",", "cos_distance", ")", "-", "tf", ".", "eye", "(", "tf", ".", "shape", "(", "x", ")", ...
[ 451, 4 ]
[ 465, 9 ]
python
en
['en', 'en', 'en']
True
SNNLCrossEntropy.same_label_mask
(y, y2)
Masking matrix such that element i,j is 1 iff y[i] == y2[i]. :param y: a list of labels :param y2: a list of labels :returns: A tensor for the masking matrix.
Masking matrix such that element i,j is 1 iff y[i] == y2[i]. :param y: a list of labels :param y2: a list of labels
def same_label_mask(y, y2): """Masking matrix such that element i,j is 1 iff y[i] == y2[i]. :param y: a list of labels :param y2: a list of labels :returns: A tensor for the masking matrix. """ return tf.cast(tf.squeeze(tf.equal(y, tf.expand_dims(y2, 1))), tf.float32)
[ "def", "same_label_mask", "(", "y", ",", "y2", ")", ":", "return", "tf", ".", "cast", "(", "tf", ".", "squeeze", "(", "tf", ".", "equal", "(", "y", ",", "tf", ".", "expand_dims", "(", "y2", ",", "1", ")", ")", ")", ",", "tf", ".", "float32", ...
[ 468, 4 ]
[ 475, 82 ]
python
en
['en', 'cy', 'en']
True
SNNLCrossEntropy.masked_pick_probability
(x, y, temp, cos_distance)
The pairwise sampling probabilities for the elements of x for neighbor points which share labels. :param x: a matrix :param y: a list of labels for each element of x :param temp: Temperature :cos_distance: Boolean for using cosine or Euclidean distance :returns: A tensor...
The pairwise sampling probabilities for the elements of x for neighbor points which share labels. :param x: a matrix :param y: a list of labels for each element of x :param temp: Temperature :cos_distance: Boolean for using cosine or Euclidean distance
def masked_pick_probability(x, y, temp, cos_distance): """The pairwise sampling probabilities for the elements of x for neighbor points which share labels. :param x: a matrix :param y: a list of labels for each element of x :param temp: Temperature :cos_distance: Boolean ...
[ "def", "masked_pick_probability", "(", "x", ",", "y", ",", "temp", ",", "cos_distance", ")", ":", "return", "SNNLCrossEntropy", ".", "pick_probability", "(", "x", ",", "temp", ",", "cos_distance", ")", "*", "SNNLCrossEntropy", ".", "same_label_mask", "(", "y",...
[ 478, 4 ]
[ 490, 50 ]
python
en
['en', 'en', 'en']
True
SNNLCrossEntropy.SNNL
(x, y, temp, cos_distance)
Soft Nearest Neighbor Loss :param x: a matrix. :param y: a list of labels for each element of x. :param temp: Temperature. :cos_distance: Boolean for using cosine or Euclidean distance. :returns: A tensor for the Soft Nearest Neighbor Loss of the points in x wi...
Soft Nearest Neighbor Loss :param x: a matrix. :param y: a list of labels for each element of x. :param temp: Temperature. :cos_distance: Boolean for using cosine or Euclidean distance.
def SNNL(x, y, temp, cos_distance): """Soft Nearest Neighbor Loss :param x: a matrix. :param y: a list of labels for each element of x. :param temp: Temperature. :cos_distance: Boolean for using cosine or Euclidean distance. :returns: A tensor for the Soft Nearest Neighb...
[ "def", "SNNL", "(", "x", ",", "y", ",", "temp", ",", "cos_distance", ")", ":", "summed_masked_pick_prob", "=", "tf", ".", "reduce_sum", "(", "SNNLCrossEntropy", ".", "masked_pick_probability", "(", "x", ",", "y", ",", "temp", ",", "cos_distance", ")", ",",...
[ 493, 4 ]
[ 508, 9 ]
python
en
['es', 'lb', 'en']
False
SNNLCrossEntropy.optimized_temp_SNNL
(x, y, initial_temp, cos_distance)
The optimized variant of Soft Nearest Neighbor Loss. Every time this tensor is evaluated, the temperature is optimized to minimize the loss value, this results in more numerically stable calculations of the SNNL. :param x: a matrix. :param y: a list of labels for each element of x. ...
The optimized variant of Soft Nearest Neighbor Loss. Every time this tensor is evaluated, the temperature is optimized to minimize the loss value, this results in more numerically stable calculations of the SNNL. :param x: a matrix. :param y: a list of labels for each element of x. ...
def optimized_temp_SNNL(x, y, initial_temp, cos_distance): """The optimized variant of Soft Nearest Neighbor Loss. Every time this tensor is evaluated, the temperature is optimized to minimize the loss value, this results in more numerically stable calculations of the SNNL. :param x: a m...
[ "def", "optimized_temp_SNNL", "(", "x", ",", "y", ",", "initial_temp", ",", "cos_distance", ")", ":", "t", "=", "tf", ".", "Variable", "(", "1", ",", "dtype", "=", "tf", ".", "float32", ",", "trainable", "=", "False", ",", "name", "=", "\"temp\"", ")...
[ 511, 4 ]
[ 533, 67 ]
python
en
['en', 'en', 'en']
True
StaticUtilsTests.test_was_modified_since_fp
(self)
Test that a floating point mtime does not disturb was_modified_since. (#18675)
Test that a floating point mtime does not disturb was_modified_since. (#18675)
def test_was_modified_since_fp(self): """ Test that a floating point mtime does not disturb was_modified_since. (#18675) """ mtime = 1343416141.107817 header = http_date(mtime) self.assertFalse(was_modified_since(header, mtime))
[ "def", "test_was_modified_since_fp", "(", "self", ")", ":", "mtime", "=", "1343416141.107817", "header", "=", "http_date", "(", "mtime", ")", "self", ".", "assertFalse", "(", "was_modified_since", "(", "header", ",", "mtime", ")", ")" ]
[ 114, 4 ]
[ 121, 59 ]
python
en
['en', 'error', 'th']
False
compress_kml
(kml)
Return compressed KMZ from the given KML string.
Return compressed KMZ from the given KML string.
def compress_kml(kml): "Return compressed KMZ from the given KML string." kmz = BytesIO() with zipfile.ZipFile(kmz, 'a', zipfile.ZIP_DEFLATED) as zf: zf.writestr('doc.kml', kml.encode(settings.DEFAULT_CHARSET)) kmz.seek(0) return kmz.read()
[ "def", "compress_kml", "(", "kml", ")", ":", "kmz", "=", "BytesIO", "(", ")", "with", "zipfile", ".", "ZipFile", "(", "kmz", ",", "'a'", ",", "zipfile", ".", "ZIP_DEFLATED", ")", "as", "zf", ":", "zf", ".", "writestr", "(", "'doc.kml'", ",", "kml", ...
[ 14, 0 ]
[ 20, 21 ]
python
en
['en', 'en', 'en']
True
render_to_kml
(*args, **kwargs)
Render the response as KML (using the correct MIME type).
Render the response as KML (using the correct MIME type).
def render_to_kml(*args, **kwargs): "Render the response as KML (using the correct MIME type)." return HttpResponse( loader.render_to_string(*args, **kwargs), content_type='application/vnd.google-earth.kml+xml', )
[ "def", "render_to_kml", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "HttpResponse", "(", "loader", ".", "render_to_string", "(", "*", "args", ",", "*", "*", "kwargs", ")", ",", "content_type", "=", "'application/vnd.google-earth.kml+xml'", ...
[ 23, 0 ]
[ 28, 5 ]
python
en
['en', 'en', 'en']
True
render_to_kmz
(*args, **kwargs)
Compress the KML content and return as KMZ (using the correct MIME type).
Compress the KML content and return as KMZ (using the correct MIME type).
def render_to_kmz(*args, **kwargs): """ Compress the KML content and return as KMZ (using the correct MIME type). """ return HttpResponse( compress_kml(loader.render_to_string(*args, **kwargs)), content_type='application/vnd.google-earth.kmz', )
[ "def", "render_to_kmz", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "HttpResponse", "(", "compress_kml", "(", "loader", ".", "render_to_string", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", ",", "content_type", "=", "'applicati...
[ 31, 0 ]
[ 39, 5 ]
python
en
['en', 'error', 'th']
False
get_requirement_info
(dist)
Compute and return values (req, editable, comments) for use in FrozenRequirement.from_dist().
Compute and return values (req, editable, comments) for use in FrozenRequirement.from_dist().
def get_requirement_info(dist): # type: (Distribution) -> RequirementInfo """ Compute and return values (req, editable, comments) for use in FrozenRequirement.from_dist(). """ if not dist_is_editable(dist): return (None, False, []) location = os.path.normcase(os.path.abspath(dist.lo...
[ "def", "get_requirement_info", "(", "dist", ")", ":", "# type: (Distribution) -> RequirementInfo", "if", "not", "dist_is_editable", "(", "dist", ")", ":", "return", "(", "None", ",", "False", ",", "[", "]", ")", "location", "=", "os", ".", "path", ".", "norm...
[ 175, 0 ]
[ 234, 34 ]
python
en
['en', 'error', 'th']
False
blankout
(src, char)
Change every non-whitespace character to the given char. Used in the templatize function.
Change every non-whitespace character to the given char. Used in the templatize function.
def blankout(src, char): """ Change every non-whitespace character to the given char. Used in the templatize function. """ return dot_re.sub(char, src)
[ "def", "blankout", "(", "src", ",", "char", ")", ":", "return", "dot_re", ".", "sub", "(", "char", ",", "src", ")" ]
[ 11, 0 ]
[ 16, 32 ]
python
en
['en', 'error', 'th']
False
templatize
(src, origin=None)
Turn a Django template into something that is understood by xgettext. It does so by translating the Django translation tags into standard gettext function invocations.
Turn a Django template into something that is understood by xgettext. It does so by translating the Django translation tags into standard gettext function invocations.
def templatize(src, origin=None): """ Turn a Django template into something that is understood by xgettext. It does so by translating the Django translation tags into standard gettext function invocations. """ out = StringIO('') message_context = None intrans = False inplural = False...
[ "def", "templatize", "(", "src", ",", "origin", "=", "None", ")", ":", "out", "=", "StringIO", "(", "''", ")", "message_context", "=", "None", "intrans", "=", "False", "inplural", "=", "False", "trimmed", "=", "False", "singular", "=", "[", "]", "plura...
[ 34, 0 ]
[ 226, 25 ]
python
en
['en', 'error', 'th']
False