code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''Compute the bezout algorithm of a and b, i.e. it returns u, v, p such as:
p = GCD(a,b)
a * u + b * v = p
Copied from http://www.labri.fr/perso/betrema/deug/poly/euclide.html.
'''
u = 1
v = 0
s = 0
t = 1
while b > 0:
q = a // b
r = a % b
... | def bezout(a, b) | Compute the bezout algorithm of a and b, i.e. it returns u, v, p such as:
p = GCD(a,b)
a * u + b * v = p
Copied from http://www.labri.fr/perso/betrema/deug/poly/euclide.html. | 4.042241 | 1.563457 | 2.58545 |
'''Converts the integer x to its big-endian representation of length
x_len.
'''
if x > 256**x_len:
raise exceptions.IntegerTooLarge
h = hex(x)[2:]
if h[-1] == 'L':
h = h[:-1]
if len(h) & 1 == 1:
h = '0%s' % h
x = binascii.unhexlify(h)
return b'\x00' * int(x... | def i2osp(x, x_len) | Converts the integer x to its big-endian representation of length
x_len. | 3.273374 | 2.671055 | 1.225499 |
'''Computes the XOR operator between two byte strings. If the strings are
of different lengths, the result string is as long as the shorter.
'''
if sys.version_info[0] < 3:
return ''.join((chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)))
else:
return bytes(x ^ y for (x, y) in zip(a,... | def string_xor(a, b) | Computes the XOR operator between two byte strings. If the strings are
of different lengths, the result string is as long as the shorter. | 2.953648 | 1.88129 | 1.570012 |
'''
Accumulate random bit string and remove \0 bytes until the needed length
is obtained.
'''
result = []
i = 0
while i < length:
rnd = rnd.getrandbits(12*length)
s = i2osp(rnd, 3*length)
s = s.replace('\x00', '')
result.append(s)
i += len(s)
... | def get_nonzero_random_bytes(length, rnd=default_crypto_random) | Accumulate random bit string and remove \0 bytes until the needed length
is obtained. | 6.155799 | 3.257735 | 1.889595 |
'''Compare two strings using constant time.'''
result = True
for x, y in zip(a, b):
result &= (x == y)
return result | def constant_time_cmp(a, b) | Compare two strings using constant time. | 3.894249 | 4.330297 | 0.899303 |
'''Encrypt a byte message using a RSA public key and the OAEP wrapping
algorithm,
Parameters:
public_key - an RSA public key
message - a byte string
label - a label a per-se PKCS#1 standard
hash_class - a Python class for a message digest algorithme respecting
the... | def encrypt(public_key, message, label=b'', hash_class=hashlib.sha1,
mgf=mgf.mgf1, seed=None, rnd=default_crypto_random) | Encrypt a byte message using a RSA public key and the OAEP wrapping
algorithm,
Parameters:
public_key - an RSA public key
message - a byte string
label - a label a per-se PKCS#1 standard
hash_class - a Python class for a message digest algorithme respecting
the hashli... | 4.056631 | 2.143211 | 1.892782 |
'''Decrypt a byte message using a RSA private key and the OAEP wrapping
algorithm
Parameters:
public_key - an RSA public key
message - a byte string
label - a label a per-se PKCS#1 standard
hash_class - a Python class for a message digest algorithme respecting
the... | def decrypt(private_key, message, label=b'', hash_class=hashlib.sha1,
mgf=mgf.mgf1) | Decrypt a byte message using a RSA private key and the OAEP wrapping
algorithm
Parameters:
public_key - an RSA public key
message - a byte string
label - a label a per-se PKCS#1 standard
hash_class - a Python class for a message digest algorithme respecting
the hashli... | 3.965205 | 2.61258 | 1.517736 |
'''Generates an RSA key pair.
size:
the bit size of the modulus, default to 512.
number:
the number of primes to use, default to 2.
rnd:
the random number generator to use, default to SystemRandom from the
random library.
k:
the num... | def generate_key_pair(size=512, number=2, rnd=default_crypto_random,
k=DEFAULT_ITERATION, primality_algorithm=None,
strict_size=True, e=0x10001) | Generates an RSA key pair.
size:
the bit size of the modulus, default to 512.
number:
the number of primes to use, default to 2.
rnd:
the random number generator to use, default to SystemRandom from the
random library.
k:
the number of ... | 3.37383 | 2.38761 | 1.413057 |
commandline = os.environ['COMMANDLINE']
args = split_args(commandline)[1:]
if args and not commandline.endswith(' '):
incomplete = args[-1]
args = args[:-1]
else:
incomplete = ''
def escape(s):
return s.replace('"', '""').replace("'", "''").replace('$', '\\$').r... | def do_zsh_complete(cli, prog_name) | Do the zsh completion
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
Returns
-------
bool
True if the completion was successful, False otherwise | 4.265158 | 4.646258 | 0.917977 |
app.connect('html-page-context', add_html_link)
app.connect('build-finished', create_sitemap)
app.set_translator('html', HTMLTranslator)
app.sitemap_links = [] | def setup(app) | Setup conntects events to the sitemap builder | 3.457663 | 3.018216 | 1.145598 |
base_url = app.config['html_theme_options'].get('base_url', '')
if base_url:
app.sitemap_links.append(base_url + pagename + ".html") | def add_html_link(app, pagename, templatename, context, doctree) | As each page is built, collect page names for the sitemap | 3.616911 | 2.994476 | 1.207861 |
if (not app.config['html_theme_options'].get('base_url', '') or
exception is not None or
not app.sitemap_links):
return
filename = app.outdir + "/sitemap.xml"
print("Generating sitemap.xml in %s" % filename)
root = ET.Element("urlset")
root.set("xmlns", "http://w... | def create_sitemap(app, exception) | Generates the sitemap.xml from the collected HTML page links | 2.554198 | 2.428091 | 1.051937 |
bits = token.split_contents()
if len(bits) == 2:
object_var = parser.compile_filter(bits[1])
language_var = None
elif len(bits) == 3:
object_var = parser.compile_filter(bits[1])
language_var = parser.compile_filter(bits[2])
else:
raise TemplateSyntaxError("'%... | def objectlanguage(parser, token) | Template tag to switch an object language
Example::
{% objectlanguage object "en" %}
{{ object.title }}
{% endobjectlanguage %}
A TranslatedObject is not affected by the ``{% language .. %}`` tag
as it maintains it's own state. This tag temporary switches the object state.
N... | 1.752206 | 1.939471 | 0.903445 |
# This is the same logic as the django-admin uses.
# The only difference is the origin of the request parameter.
if not is_multilingual_project():
# By default, the objects are stored in a single static language.
# This makes the transition to multilingual easier as well.
# The ... | def get_language_parameter(request, query_language_key='language', object=None, default=None) | Get the language parameter from the current request. | 7.439471 | 7.267632 | 1.023644 |
tabs = TabsList(css_class=css_class)
get = request.GET.copy() # QueryDict object
tab_languages = []
site_id = getattr(settings, 'SITE_ID', None)
for lang_dict in appsettings.PARLER_LANGUAGES.get(site_id, ()):
code = lang_dict['code']
title = get_language_title(code)
ge... | def get_language_tabs(request, current_language, available_languages, css_class=None) | Determine the language tabs to show. | 2.838737 | 2.860905 | 0.992252 |
if instance.pk is None or instance._state.adding:
return []
keys = []
tr_models = instance._parler_meta.get_all_models()
# TODO: performs a query to fetch the language codes. Store that in memcached too.
for language in instance.get_available_languages():
for tr_model in tr_mo... | def get_object_cache_keys(instance) | Return the cache keys associated with an object. | 4.967822 | 4.831306 | 1.028257 |
# Always cache the entire object, as this already produces
# a lot of queries. Don't go for caching individual fields.
return 'parler.{0}.{1}.{2}.{3}'.format(translated_model._meta.app_label, translated_model.__name__, master_id, language_code) | def get_translation_cache_key(translated_model, master_id, language_code) | The low-level function to get the cache key for a translation. | 6.896466 | 6.685486 | 1.031558 |
if language_code is None:
language_code = instance.get_current_language()
translated_model = instance._parler_meta.get_model_by_related_name(related_name)
values = _get_cached_values(instance, translated_model, language_code, use_fallback)
if not values:
return None
try:
... | def get_cached_translation(instance, language_code=None, related_name=None, use_fallback=False) | Fetch an cached translation.
.. versionadded 1.2 Added the ``related_name`` parameter. | 3.773689 | 3.915734 | 0.963725 |
if language_code is None:
language_code = instance.get_current_language()
# In django-parler 1.1 the order of the arguments was fixed, It used to be language_code, field_name
# This serves as detection against backwards incompatibility issues.
if len(field_name) <= 5 and len(language_code)... | def get_cached_translated_field(instance, field_name, language_code=None, use_fallback=False) | Fetch an cached field. | 5.315305 | 5.201552 | 1.021869 |
if not appsettings.PARLER_ENABLE_CACHING or not instance.pk or instance._state.adding:
return None
key = get_translation_cache_key(translated_model, instance.pk, language_code)
values = cache.get(key)
if not values:
return None
# Check for a stored fallback marker
if value... | def _get_cached_values(instance, translated_model, language_code, use_fallback=False) | Fetch an cached field. | 4.652738 | 4.564831 | 1.019257 |
if not appsettings.PARLER_ENABLE_CACHING:
return
if translation.master_id is None:
raise ValueError("Can't cache unsaved translation")
# Cache a translation object.
# For internal usage, object parameters are not suited for outside usage.
fields = translation.get_translated_fi... | def _cache_translation(translation, timeout=cache.default_timeout) | Store a new translation in the cache. | 4.502793 | 4.255074 | 1.058217 |
if not appsettings.PARLER_ENABLE_CACHING or not instance.pk or instance._state.adding:
return
tr_model = instance._parler_meta.get_model_by_related_name(related_name)
key = get_translation_cache_key(tr_model, instance.pk, language_code)
cache.set(key, {'__FALLBACK__': True}, timeout=timeou... | def _cache_translation_needs_fallback(instance, language_code, related_name, timeout=cache.default_timeout) | Store the fact that a translation doesn't exist, and the fallback should be used. | 3.854444 | 3.692205 | 1.043941 |
if not isinstance(template_name_list, tuple):
template_name_list = tuple(template_name_list)
try:
return _cached_name_lookups[template_name_list]
except KeyError:
# Find which template of the template_names is selected by the Django loader.
for template_name in template... | def select_template_name(template_name_list, using=None) | Given a list of template names, find the first one that exists. | 3.442333 | 3.247493 | 1.059997 |
if not self.view_url_name:
# Sadly, class based views can't work with reverse(func_pointer) as that's unknown.
# Neither is it possible to use resolve(self.request.path).view_name in this function as auto-detection.
# This function can be called in the context of a d... | def get_view_url(self) | This method is used by the ``get_translated_url`` template tag.
By default, it uses the :attr:`view_url_name` to generate an URL.
When the URL ``args`` and ``kwargs`` are translatable,
override this function instead to generate the proper URL. | 7.568701 | 7.289625 | 1.038284 |
if queryset is None:
queryset = self.get_queryset()
slug = self.kwargs[self.slug_url_kwarg]
choices = self.get_language_choices()
obj = None
using_fallback = False
prev_choices = []
for lang_choice in choices:
try:
... | def get_object(self, queryset=None) | Fetch the object using a translated slug. | 6.294689 | 6.024673 | 1.044818 |
object = super(LanguageChoiceMixin, self).get_object(queryset)
if isinstance(object, TranslatableModelMixin):
object.set_current_language(self.get_language(), initialize=True)
return object | def get_object(self, queryset=None) | Assign the language for the retrieved object. | 4.608684 | 3.748581 | 1.229448 |
return get_language_parameter(self.request, self.query_language_key, default=self.get_default_language(object=object)) | def get_language(self) | Get the language parameter from the current request. | 9.296394 | 7.46139 | 1.245933 |
current_language = self.get_current_language()
if self.object:
available_languages = list(self.object.get_available_languages())
else:
available_languages = []
return get_language_tabs(self.request, current_language, available_languages) | def get_language_tabs(self) | Determine the language tabs to show. | 2.97198 | 2.812119 | 1.056847 |
super_method = super(TranslatableModelFormMixin, self).get_form_class
# no "__func__" on the class level function in python 3
default_method = getattr(ModelFormMixin.get_form_class, '__func__', ModelFormMixin.get_form_class)
if not (super_method.__func__ is default_method):
... | def get_form_class(self) | Return a ``TranslatableModelForm`` by default if no form_class is set. | 4.252863 | 3.897145 | 1.091277 |
kwargs = super(TranslatableModelFormMixin, self).get_form_kwargs()
# The TranslatableAdmin can set form.language_code, because the modeladmin always creates a fresh subclass.
# If that would be done here, the original globally defined form class would be updated.
kwargs['_curren... | def get_form_kwargs(self) | Pass the current language to the form. | 11.017241 | 9.619438 | 1.14531 |
languages_list = LanguagesSetting(languages_list)
languages_list.setdefault('default', {})
defaults = languages_list['default']
defaults.setdefault('hide_untranslated', False) # Whether queries with .active_translations() may or may not return the fallback language.
if 'fallback' in default... | def add_default_language_settings(languages_list, var_name='PARLER_LANGUAGES', **extra_defaults) | Apply extra defaults to the language settings.
This function can also be used by other packages to
create their own variation of ``PARLER_LANGUAGES`` with extra fields.
For example::
from django.conf import settings
from parler import appsettings as parler_appsettings
# Create loca... | 3.350091 | 3.349164 | 1.000277 |
valid_keys = ['code', 'fallbacks', 'hide_untranslated',
'redirect_on_fallback']
if cms_languages:
if sys.version_info < (3, 0, 0):
int_types = (int, long)
else:
int_types = int
parler_languages = copy.deepcopy(cms_languages)
for sit... | def get_parler_languages_from_django_cms(cms_languages=None) | Converts django CMS' setting CMS_LANGUAGES into PARLER_LANGUAGES. Since
CMS_LANGUAGES is a strict superset of PARLER_LANGUAGES, we do a bit of
cleansing to remove irrelevant items. | 2.250924 | 2.141803 | 1.050948 |
if language_code is None:
raise ValueError(get_null_language_error())
if site_id is None:
site_id = getattr(settings, 'SITE_ID', None)
for lang_dict in self.get(site_id, ()):
if lang_dict['code'] == language_code:
return lang_dict
... | def get_language(self, language_code, site_id=None) | Return the language settings for the current site
This function can be used with other settings variables
to support modules which create their own variation of the ``PARLER_LANGUAGES`` setting.
For an example, see :func:`~parler.appsettings.add_default_language_settings`. | 3.15621 | 3.075123 | 1.026369 |
if language_code is None:
language_code = get_language()
lang_dict = self.get_language(language_code, site_id=site_id)
if not lang_dict['hide_untranslated']:
return [language_code] + [lang for lang in lang_dict['fallbacks'] if lang != language_code]
else... | def get_active_choices(self, language_code=None, site_id=None) | Find out which translations should be visible in the site.
It returns a list with either a single choice (the current language),
or a list with the current language + fallback language. | 2.779804 | 2.462477 | 1.128865 |
choices = self.get_active_choices(language_code, site_id=site_id)
return choices[1:] | def get_fallback_languages(self, language_code=None, site_id=None) | Find out what the fallback language is for a given language choice.
.. versionadded 1.5 | 5.910148 | 7.167292 | 0.8246 |
choices = self.get_active_choices(language_code, site_id=site_id)
if choices and len(choices) > 1:
# Still take the last, like previous code.
# With multiple fallback languages that means taking the base language.
# Hence, upgrade the code to use get_fallback... | def get_fallback_language(self, language_code=None, site_id=None) | Find out what the fallback language is for a given language choice.
.. deprecated:: 1.5
Use :func:`get_fallback_languages` instead. | 8.910695 | 8.458101 | 1.05351 |
if site_id is None:
site_id = getattr(settings, 'SITE_ID', None)
try:
return self[site_id][0]['code']
except (KeyError, IndexError):
# No configuration, always fallback to default language.
# This is essentially a non-multilingual configu... | def get_first_language(self, site_id=None) | Return the first language for the current site.
This can be used for user interfaces, where the languages are displayed in tabs. | 4.578582 | 4.238543 | 1.080226 |
field = model._meta.get_field(name)
if not field.editable: # see fields_for_model() logic in Django.
return None
# Apply admin formfield_overrides
if formfield_callback is None:
formfield = field.formfield(**kwargs)
elif not callable(formfield_callback):
raise TypeErro... | def _get_model_form_field(model, name, formfield_callback=None, **kwargs) | Utility to create the formfield from a model field.
When a field is not editable, a ``None`` will be returned. | 3.105025 | 3.118346 | 0.995728 |
fields = {}
# Collect all translated fields {'name': 'value'}
for field in self._translated_fields:
try:
value = self.cleaned_data[field]
except KeyError: # Field has a ValidationError
continue
fields[field] = value
... | def save_translated_fields(self) | Save all translated fields. | 4.991388 | 4.914801 | 1.015583 |
if not meta:
meta = {}
if shared_model._meta.abstract:
# This can't be done, because `master = ForeignKey(shared_model)` would fail.
raise TypeError("Can't create TranslatedFieldsModel for abstract class {0}".format(shared_model.__name__))
# Define inner Meta class
meta['a... | def create_translations_model(shared_model, related_name, meta, **fields) | Dynamically create the translations model.
Create the translations model for the shared model 'model'.
:param related_name: The related name for the reverse FK from the translations model.
:param meta: A (optional) dictionary of attributes for the translations model's inner Meta class.
:param fields: A... | 3.976322 | 3.895781 | 1.020674 |
objects = [] # no generator, make sure objects are all filled first
for parler_meta, model_fields in self._parler_meta._split_fields(**fields):
translation = self._get_translated_model(language_code=language_code, auto_create=True, meta=parler_meta)
for field, value in ... | def _set_translated_fields(self, language_code=None, **fields) | Assign fields to the translated models. | 5.994309 | 5.511597 | 1.087581 |
if language_code is None:
raise ValueError(get_null_language_error())
meta = self._parler_meta
if self._translations_cache[meta.root_model].get(language_code, None): # MISSING evaluates to False too
raise ValueError("Translation already exists: {0}".format(lang... | def create_translation(self, language_code, **fields) | Add a translation to the model.
The :func:`save_translations` function is called afterwards.
The object will be saved immediately, similar to
calling :func:`~django.db.models.manager.Manager.create`
or :func:`~django.db.models.fields.related.RelatedManager.create` on related fields. | 6.935459 | 7.077195 | 0.979973 |
if language_code is None:
raise ValueError(get_null_language_error())
if related_name is None:
metas = self._parler_meta
else:
metas = [self._parler_meta[related_name]]
num_deleted = 0
for meta in metas:
try:
... | def delete_translation(self, language_code, related_name=None) | Delete a translation from a model.
:param language_code: The language to remove.
:param related_name: If given, only the model matching that related_name is removed. | 3.783389 | 3.885535 | 0.973711 |
self._current_language = normalize_language_code(language_code or get_language())
# Ensure the translation is present for __get__ queries.
if initialize:
self._get_translated_model(use_fallback=False, auto_create=True) | def set_current_language(self, language_code, initialize=False) | Switch the currently activate language of the object. | 8.292472 | 8.344862 | 0.993722 |
lang_dict = get_language_settings(self._current_language)
fallbacks = [lang for lang in lang_dict['fallbacks'] if lang != self._current_language]
return fallbacks or [] | def get_fallback_languages(self) | Return the fallback language codes,
which are used in case there is no translation for the currently active language. | 4.643499 | 4.048016 | 1.147105 |
if language_code is None:
language_code = self._current_language
if language_code is None:
raise ValueError(get_null_language_error())
meta = self._parler_meta._get_extension_by_related_name(related_name)
try:
# Check the local cache... | def has_translation(self, language_code=None, related_name=None) | Return whether a translation for the given language exists.
Defaults to the current language code.
.. versionadded 1.2 Added the ``related_name`` parameter. | 6.481234 | 6.32505 | 1.024693 |
meta = self._parler_meta._get_extension_by_related_name(related_name)
prefetch = self._get_prefetched_translations(meta=meta)
if prefetch is not None:
# TODO: this will break when using custom Django 1.8 Prefetch objects?
db_languages = sorted(obj.language_code ... | def get_available_languages(self, related_name=None, include_unsaved=False) | Return the language codes of all translated variations.
.. versionadded 1.2 Added the ``include_unsaved`` and ``related_name`` parameters. | 4.375392 | 4.545208 | 0.962639 |
meta = self._parler_meta._get_extension_by_related_name(related_name)
return self._get_translated_model(language_code, meta=meta) | def get_translation(self, language_code, related_name=None) | Fetch the translated model | 7.710735 | 6.991367 | 1.102894 |
if meta is None:
meta = self._parler_meta.root
tr_model = meta.model
local_cache = self._translations_cache[tr_model]
if local_cache:
# There is already a language available in the case. No need for queries.
# Give consistent answers if they ... | def _get_any_translated_model(self, meta=None) | Return any available translation.
Returns None if there are no translations at all. | 4.723749 | 4.491239 | 1.05177 |
# Get via self.TRANSLATIONS_FIELD.get(..) so it also uses the prefetch/select_related cache.
if meta is None:
meta = self._parler_meta.root
accessor = getattr(self, meta.rel_name) # RelatedManager
return accessor.get_queryset() | def _get_translated_queryset(self, meta=None) | Return the queryset that points to the translated model.
If there is a prefetch, it can be read from this queryset. | 15.941734 | 14.248675 | 1.118822 |
if meta is None:
meta = self._parler_meta.root
related_name = meta.rel_name
try:
# Read the list directly, avoid QuerySet construction.
# Accessing self._get_translated_queryset(parler_meta)._prefetch_done is more expensive.
return self._... | def _get_prefetched_translations(self, meta=None) | Return the queryset with prefetch results. | 9.318112 | 8.198388 | 1.136579 |
# This is called from ModelForm._post_clean() or Model.full_clean()
errors = {}
try:
super(TranslatableModelMixin, self).validate_unique(exclude=exclude)
except ValidationError as e:
errors = e.message_dict
for local_cache in six.itervalues(self.... | def validate_unique(self, exclude=None) | Also validate the unique_together of the translated model. | 3.763054 | 3.445884 | 1.092043 |
# Copy cache, new objects (e.g. fallbacks) might be fetched if users override save_translation()
# Not looping over the cache, but using _parler_meta so the translations are processed in the order of inheritance.
local_caches = self._translations_cache.copy()
for meta in self._p... | def save_translations(self, *args, **kwargs) | The method to save all translations.
This can be overwritten to implement any custom additions.
This method calls :func:`save_translation` for every fetched language.
:param args: Any custom arguments to pass to :func:`save`.
:param kwargs: Any custom arguments to pass to :func:`save`. | 10.616898 | 10.425309 | 1.018377 |
if self.pk is None or self._state.adding:
raise RuntimeError("Can't save translations when the master object is not yet saved.")
# Translation models without any fields are also supported.
# This is useful for parent objects that have inlines;
# the parent object de... | def save_translation(self, translation, *args, **kwargs) | Save the translation when it's modified, or unsaved.
.. note::
When a derived model provides additional translated fields,
this method receives both the original and extended translation.
To distinguish between both objects, check for ``translation.related_name``.
:pa... | 7.970369 | 7.984086 | 0.998282 |
meta = self._parler_meta._get_extension_by_field(field)
# Extra feature: query a single field from a other translation.
if language_code and language_code != self._current_language:
try:
tr_model = self._get_translated_model(language_code, meta=meta, use_fal... | def safe_translation_getter(self, field, default=None, language_code=None, any_language=False) | Fetch a translated property, and return a default value
when both the translation and fallback language are missing.
When ``any_language=True`` is used, the function also looks
into other languages to find a suitable value. This feature can be useful
for "title" attributes for example, ... | 4.724833 | 5.132078 | 0.920647 |
try:
return self._fields_to_model[name]
except KeyError:
raise FieldError("Translated field does not exist: '{0}'".format(name)) | def get_model_by_field(self, name) | Find the :class:`TranslatedFieldsModel` that contains the given field. | 5.200353 | 4.031229 | 1.290017 |
if name is None:
raise TypeError("Expected field name")
# Reuse existing lookups.
tr_model = self.get_model_by_field(name)
for meta in self._extensions:
if meta.model == tr_model:
return meta | def _get_extension_by_field(self, name) | Find the ParlerOptions object that corresponds with the given translated field. | 7.365159 | 6.231816 | 1.181864 |
if related_name is None:
return self._extensions[0]
for meta in self._extensions:
if meta.rel_name == related_name:
return meta
raise ValueError("No translated model of '{0}' has a reverse name of '{1}'".format(
self.root.shared_mode... | def _get_extension_by_related_name(self, related_name) | Find which model is connected to a given related name.
If the related name is ``None``, the :attr:`root_model` will be returned. | 5.623057 | 5.139959 | 1.093989 |
if not new_class.master or not isinstance(new_class.master, ForwardManyToOneDescriptor):
raise ImproperlyConfigured("{0}.master should be a ForeignKey to the shared table.".format(new_class.__name__))
remote_field = new_class.master.field.remote_field
shared_model = remote_field.model
met... | def _validate_master(new_class) | Check whether the 'master' field on a TranslatedFieldsModel is correctly configured. | 3.129448 | 2.897059 | 1.080215 |
translations_model = self.field.meta.model
if translations_model is None:
# This only happens with abstract models. The code is accessing the descriptor at the base model directly,
# not the upgraded descriptor version that contribute_translations() installed.
... | def short_description(self) | Ensure that the admin ``list_display`` renders the correct verbose name for translated fields.
The :func:`~django.contrib.admin.utils.label_for_field` function
uses :func:`~django.db.models.Options.get_field_by_name` to find the find and ``verbose_name``.
However, for translated fields, this op... | 11.322444 | 9.508699 | 1.190746 |
if obj is not None:
return obj.get_current_language()
else:
return self._language(request) | def get_form_language(self, request, obj=None) | Return the current language for the currently displayed object fields. | 4.798983 | 3.872871 | 1.239128 |
qs = super(BaseTranslatableAdmin, self).get_queryset(request)
if self._has_translatable_model():
if not isinstance(qs, TranslatableQuerySet):
raise ImproperlyConfigured("{0} class does not inherit from TranslatableQuerySet".format(qs.__class__.__name__))
... | def get_queryset(self, request) | Make sure the current language is selected. | 3.511046 | 3.170254 | 1.107497 |
current_language = self.get_form_language(request, obj)
return get_language_tabs(request, current_language, available_languages, css_class=css_class) | def get_language_tabs(self, request, obj, available_languages, css_class=None) | Determine the language tabs to show. | 2.922226 | 2.696316 | 1.083785 |
all_languages = [code for code, __ in settings.LANGUAGES]
return mark_safe(
self._languages_column(
object, all_languages, span_classes='all-languages'
)
) | def all_languages_column(self, object) | The language column which can be included in the ``list_display``.
It also shows untranslated languages | 5.908676 | 6.60718 | 0.894281 |
if obj:
return obj.get_available_languages()
else:
return self.model._parler_meta.root_model.objects.none() | def get_available_languages(self, obj) | Fetching the available languages as queryset. | 5.07732 | 4.103711 | 1.237251 |
obj = super(TranslatableAdmin, self).get_object(request, object_id, *args, **kwargs)
if obj is not None and self._has_translatable_model(): # Allow fallback to regular models.
obj.set_current_language(self._language(request, obj), initialize=True)
return obj | def get_object(self, request, object_id, *args, **kwargs) | Make sure the object is fetched in the correct language. | 5.373897 | 4.774461 | 1.12555 |
form_class = super(TranslatableAdmin, self).get_form(request, obj, **kwargs)
if self._has_translatable_model():
form_class.language_code = self.get_form_language(request, obj)
return form_class | def get_form(self, request, obj=None, **kwargs) | Pass the current language to the form. | 3.425081 | 2.780797 | 1.231691 |
urlpatterns = super(TranslatableAdmin, self).get_urls()
if not self._has_translatable_model():
return urlpatterns
else:
opts = self.model._meta
info = opts.app_label, opts.model_name
return [url(
r'^(.+)/change/delete-trans... | def get_urls(self) | Add a delete-translation view. | 2.663945 | 2.310055 | 1.153195 |
if self._has_translatable_model():
lang_code = self.get_form_language(request, obj)
lang = get_language_title(lang_code)
available_languages = self.get_available_languages(obj)
language_tabs = self.get_language_tabs(request, obj, available_languages)
... | def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None) | Insert the language tabs. | 4.39567 | 4.223982 | 1.040646 |
opts = self.model._meta
root_model = self.model._parler_meta.root_model
# Get object and translation
shared_obj = self.get_object(request, unquote(object_id))
if shared_obj is None:
raise Http404
shared_obj.set_current_language(language_code)
... | def delete_translation(self, request, object_id, language_code) | The 'delete translation' admin view for this model. | 2.734712 | 2.7403 | 0.997961 |
opts = self.model._meta
context = {
'object': obj.master,
'language_code': language_code,
'opts': opts,
'app_label': opts.app_label,
'language_name': get_language_title(language_code),
'object_name': force_text(opts.verbose... | def deletion_not_allowed(self, request, obj, language_code) | Deletion-not-allowed view. | 2.412692 | 2.442776 | 0.987685 |
master = translation.master
for qs in self.get_translation_objects(request, translation.language_code, obj=master, inlines=self.delete_inline_translations):
if isinstance(qs, (tuple, list)):
# The objects are deleted one by one.
# This triggers the po... | def delete_model_translation(self, request, translation) | Hook for deleting a translation.
This calls :func:`get_translation_objects` to collect all related objects for the translation.
By default, that includes the translations for inline objects. | 8.206914 | 6.776331 | 1.211115 |
if obj is not None:
# A single model can hold multiple TranslatedFieldsModel objects.
# Return them all.
for translations_model in obj._parler_meta.get_all_models():
try:
translation = translations_model.objects.get(master=obj, lan... | def get_translation_objects(self, request, language_code, obj=None, inlines=True) | Return all objects that should be deleted when a translation is deleted.
This method can yield all QuerySet objects or lists for the objects. | 4.038181 | 3.78742 | 1.066209 |
inline_instances = self.get_inline_instances(request, obj=obj)
for inline in inline_instances:
if issubclass(inline.model, TranslatableModelMixin):
# leverage inlineformset_factory() to find the ForeignKey.
# This also resolves the fk_name if it's set... | def _get_inline_translations(self, request, language_code, obj=None) | Fetch the inline translations | 4.320292 | 4.32068 | 0.99991 |
opts = self.model._meta
app_label = opts.app_label
return select_template_name((
"admin/{0}/{1}/change_form.html".format(app_label, opts.object_name.lower()),
"admin/{0}/change_form.html".format(app_label),
"admin/change_form.html"
)) | def default_change_form_template(self) | Determine what the actual `change_form_template` should be. | 2.112308 | 1.966025 | 1.074405 |
FormSet = super(TranslatableInlineModelAdmin, self).get_formset(request, obj, **kwargs)
# Existing objects already got the language code from the queryset().language() method.
# For new objects, the language code should be set here.
FormSet.language_code = self.get_form_language... | def get_formset(self, request, obj=None, **kwargs) | Return the formset, and provide the language information to the formset. | 6.338969 | 6.132802 | 1.033617 |
if self._has_translatable_parent_model():
return super(TranslatableInlineModelAdmin, self).get_form_language(request, obj=obj)
else:
# Follow the ?language parameter
return self._language(request) | def get_form_language(self, request, obj=None) | Return the current language for the currently displayed object fields. | 6.26509 | 5.836434 | 1.073445 |
if obj:
# Inlines dictate language code, not the parent model.
# Hence, not looking at obj.get_available_languages(), but see what languages
# are used by the inline objects that point to it.
filter = {
'master__{0}'.format(formset.fk.name... | def get_available_languages(self, obj, formset) | Fetching the available inline languages as queryset. | 5.36115 | 5.166878 | 1.0376 |
if language_code is None:
language_code = appsettings.PARLER_LANGUAGES.get_default_language()
self._language = language_code
return self | def language(self, language_code=None) | Set the language code to assign to objects retrieved using this QuerySet. | 4.249174 | 3.283159 | 1.294234 |
relname = self.model._parler_meta.root_rel_name
if not language_codes:
language_codes = (get_language(),)
filters = {}
for field_name, val in six.iteritems(translated_fields):
if field_name.startswith('master__'):
filters[field_name[8:]]... | def translated(self, *language_codes, **translated_fields) | Only return translated objects which of the given languages.
When no language codes are given, only the currently active language is returned.
.. note::
Due to Django `ORM limitations <https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships>`_,
... | 3.085871 | 3.262099 | 0.945977 |
# Default: (language, fallback) when hide_translated == False
# Alternative: (language,) when hide_untranslated == True
language_codes = get_active_language_choices(language_code)
return self.translated(*language_codes, **translated_fields) | def active_translations(self, language_code=None, **translated_fields) | Only return objects which are translated, or have a fallback that should be displayed.
Typically that's the currently active language and fallback language.
This should be combined with ``.distinct()``.
When ``hide_untranslated = True``, only the currently active language will be returned. | 9.49901 | 7.712478 | 1.231642 |
from parler import appsettings
# Avoid weird lookup errors.
if not language_code:
raise ValueError("Missing language_code in get_language_title()")
if appsettings.PARLER_SHOW_EXCLUDED_LANGUAGE_TABS:
# this allows to edit languages that are not enabled in current project but are alr... | def get_language_title(language_code) | Return the verbose_name for a language code.
Fallback to language_code if language is not found in settings. | 4.898557 | 4.964063 | 0.986804 |
# This method mainly exists for ease-of-use.
# the body is part of the settings, to allow third party packages
# to have their own variation of the settings with this method functionality included.
from parler import appsettings
return appsettings.PARLER_LANGUAGES.get_language(language_code, si... | def get_language_settings(language_code, site_id=None) | Return the language settings for the current site | 13.095664 | 12.936721 | 1.012286 |
from parler import appsettings
if site_id is None:
site_id = getattr(settings, 'SITE_ID', None)
return appsettings.PARLER_SHOW_EXCLUDED_LANGUAGE_TABS or site_id in appsettings.PARLER_LANGUAGES | def is_multilingual_project(site_id=None) | Whether the current Django project is configured for multilingual support. | 3.501145 | 3.18428 | 1.099509 |
from parler import appsettings
language = dj_get_language()
if language is None and appsettings.PARLER_DEFAULT_ACTIVATE:
return appsettings.PARLER_DEFAULT_LANGUAGE_CODE
else:
return language | def get_language() | Wrapper around Django's `get_language` utility.
For Django >= 1.8, `get_language` returns None in case no translation is activate.
Here we patch this behavior e.g. for back-end functionality requiring access to translated fields | 6.038131 | 5.130661 | 1.176872 |
today = time.time()
ret = struct.pack(b'=L', int(today))
return ret | def __timestamp() | Generate timestamp data for pyc header. | 8.449503 | 6.628356 | 1.274751 |
res = None
for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries:
if entry.name and entry.name.string == b"PYTHONSCRIPT":
res = entry.directory.entries[0].directory.entries[0]
break
return res | def _get_scripts_resource(pe) | Return the PYTHONSCRIPT resource entry. | 3.066594 | 2.314395 | 1.325009 |
rva = res.data.struct.OffsetToData
size = res.data.struct.Size
dump = pe.get_data(rva, size)
return dump | def _resource_dump(pe, res) | Return the dump of the given resource. | 3.664925 | 3.471171 | 1.055818 |
# Read py2exe header
current = struct.calcsize(b'iiii')
metadata = struct.unpack(b'iiii', data[:current])
# check py2exe magic number
# assert(metadata[0] == 0x78563412)
logging.info("Magic value: %x", metadata[0])
logging.info("Code bytes length: %d", metadata[3])
arcname = ''
... | def _get_co_from_dump(data) | Return the code objects from the dump. | 4.498719 | 4.263217 | 1.05524 |
py2exe_resource = _get_scripts_resource(pe)
if py2exe_resource is None:
logging.info('This is not a py2exe executable.')
if pe.__data__.find(b'pyi-windows-manifest-filename'):
logging.info('This seems a pyinstaller executable (unsupported).')
return bool(py2exe_resource) | def check_py2exe_file(pe) | Check file is a py2exe executable. | 8.814937 | 8.065891 | 1.092866 |
script_res = _get_scripts_resource(pe)
dump = _resource_dump(pe, script_res)
return _get_co_from_dump(dump) | def extract_code_objects(pe) | Extract Python code objects from a py2exe executable. | 9.434376 | 8.804336 | 1.07156 |
# assume Windows path information from the .exe
pyc_basename = ntpath.basename(co.co_filename)
pyc_name = pyc_basename + '.pyc'
if pyc_name not in IGNORE:
logging.info("Extracting %s", pyc_name)
pyc_header = _generate_pyc_header(python_version, len(co.co_code))
destination ... | def dump_to_pyc(co, python_version, output_dir) | Save given code_object as a .pyc file. | 3.089808 | 3.109445 | 0.993685 |
if output_dir is None:
output_dir = '.'
elif not os.path.exists(output_dir):
os.makedirs(output_dir)
pe = pefile.PE(filename)
is_py2exe = check_py2exe_file(pe)
if not is_py2exe:
raise ValueError('Not a py2exe executable.')
code_objects = extract_code_objects(pe)
... | def unpy2exe(filename, python_version=None, output_dir=None) | Process input params and produce output pyc files. | 2.792971 | 2.705377 | 1.032378 |
it = iter(iterable)
count = start
try:
last = next(it)
except StopIteration:
return
for val in it:
yield count, False, last
last = val
count += 1
yield count, True, last | def enum_mark_last(iterable, start=0) | Returns a generator over iterable that tells whether the current item is the last one.
Usage:
>>> iterable = range(10)
>>> for index, is_last, item in enum_mark_last(iterable):
>>> print(index, item, end='\n' if is_last else ', ') | 2.43397 | 3.025334 | 0.804529 |
self._check_alive()
request = IPCCommandLineExecutionRequest(command, timeout)
try:
self._tx_queue.put(request, timeout=timeout)
except queue.Full:
raise TxQueueFullError()
# The command could be modified by the IPCCommandLineExecutionRequest
... | def execute_cli_command(self, command, callback, timeout=None) | Executes an arbitrary CLI command on the SLCAN adapter, assuming that the adapter supports CLI commands.
The callback will be invoked from the method receive() using same thread.
If the command times out, the callback will be invoked anyway, with 'expired' flag set.
Args:
command: ... | 7.639911 | 5.378465 | 1.420463 |
self._update_callbacks.append(callback)
return self.UpdateHandlerRemover(lambda: self._update_callbacks.remove(callback)) | def add_update_handler(self, callback) | Args:
callback: The specified callback will be invoked when:
- A new node appears
- Node info for an existing node gets updated
- Node goes offline
Returns: Call remove() or try_remove() on the returned object to unregister... | 5.166883 | 5.483422 | 0.942273 |
if (self._registry[node_id].monotonic_timestamp + self.TIMEOUT) < time.monotonic():
self._call_event_handlers(self.UpdateEvent(self._registry[node_id],
self.UpdateEvent.EVENT_ID_OFFLINE))
del self._registry[node_id]
... | def get(self, node_id) | Args:
node_id: Returns an Entry instance for the given node ID.
If the requested node ID does not exist, throws KeyError. | 5.512635 | 5.425115 | 1.016132 |
for _nid, entry in self._registry.items():
if predicate(entry):
yield entry | def find_all(self, predicate) | Returns a generator that produces a sequence of Entry objects for which the predicate returned True.
Args:
predicate: A callable that returns a value coercible to bool. | 8.94867 | 8.256754 | 1.0838 |
undiscovered = self.find_all(lambda e: not e.discovered)
return len(list(undiscovered)) == 0 | def are_all_nodes_discovered(self) | Reports whether there are nodes whose node info is still unknown. | 6.10467 | 5.247704 | 1.163303 |
def proxy(*args):
hook(*args)
self._io_hooks.append(proxy)
return self.HookRemover(lambda: self._io_hooks.remove(proxy)) | def add_io_hook(self, hook) | Args:
hook: This hook will be invoked for every incoming and outgoing CAN frame.
Hook arguments: (direction, frame)
See FRAME_DIRECTION_*, CANFrame. | 5.24297 | 7.026059 | 0.746218 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.