code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
(desc_type, max_units) = description_type
results = [None] * max_units
self.elk._descriptions_in_progress[desc_type] = (max_units,
results,
self._got_desc)
self.elk.... | def get_descriptions(self, description_type) | Gets the descriptions for specified type.
When complete the callback is called with a list of descriptions | 9.247909 | 9.042818 | 1.02268 |
url = self.attributes['canonicalurl']
assert isinstance(url, str)
return url | def page_url(self) -> str | (:class:`str`) The canonical url of the page. | 12.986224 | 7.198935 | 1.803909 |
r
images = self.attributes.get('imageinfo', [])
if images and isinstance(images, collections.abc.Sequence):
return images[0]['url']
return None | def image_url(self) -> Optional[str] | r"""(:class:`~typing.Optional`\ [:class:`str`]) The image url.
It may be :const:`None` if it's not an image. | 7.556413 | 7.661724 | 0.986255 |
r
images = self.attributes.get('imageinfo', [])
if images and isinstance(images, collections.abc.Sequence):
img = images[0]
return img['width'], img['height']
return None | def image_resolution(self) -> Optional[Tuple[int, int]] | r"""(:class:`~typing.Optional`\ [:class:`~typing.Tuple`\ [:class:`int`,
:class:`int`]]) The (width, height) pair of the image.
It may be :const:`None` if it's not an image. | 6.367239 | 5.945651 | 1.070907 |
r
images = self.attributes.get('imageinfo', [])
if images and isinstance(images, collections.abc.Sequence):
return images[0]['size']
return None | def image_size(self) -> Optional[int] | r"""(:class:`~typing.Optional`\ [:class:`int`]) The size of the image
in bytes. It may be :const:`None` if it's not an image. | 8.250525 | 8.002499 | 1.030994 |
if not isinstance(locale, Locale):
locale = Locale.parse(locale.replace('-', '_'))
return str(locale) | def normalize_locale_code(locale: Union[Locale, str]) -> str | Determine the normalized locale code string.
>>> normalize_locale_code('ko-kr')
'ko_KR'
>>> normalize_locale_code('zh_TW')
'zh_Hant_TW'
>>> normalize_locale_code(Locale.parse('en_US'))
'en_US' | 4.392128 | 5.057474 | 0.868443 |
try:
entity = self.identity_map[entity_id]
except KeyError:
entity = Entity(entity_id, self)
self.identity_map[entity_id] = entity
if load:
entity.load()
return entity | def get(self, entity_id: EntityId, load: bool = False) -> Entity | Get a Wikidata entity by its :class:`~.entity.EntityId`.
:param entity_id: The :attr:`~.entity.Entity.id` of
the :class:`~.entity.Entity` to find.
:type eneity_id: :class:`~.entity.EntityId`
:param load: Eager loading on :const:`True`.
Lazy loading... | 2.383628 | 2.826237 | 0.843393 |
r
if not self.entity_type_guess:
return None
if entity_id[0] == 'Q':
return EntityType.item
elif entity_id[0] == 'P':
return EntityType.property
return None | def guess_entity_type(self, entity_id: EntityId) -> Optional[EntityType] | r"""Guess :class:`~.entity.EntityType` from the given
:class:`~.entity.EntityId`. It could return :const:`None` when it
fails to guess.
.. note::
It always fails to guess when :attr:`entity_type_guess`
is configued to :const:`False`.
:return: The guessed :class:... | 4.643575 | 4.860523 | 0.955365 |
decode = cast(Callable[[Client, str, Mapping[str, object]], object],
self.datavalue_decoder)
return decode(self, datatype, datavalue) | def decode_datavalue(self,
datatype: str,
datavalue: Mapping[str, object]) -> object | Decode the given ``datavalue`` using the configured
:attr:`datavalue_decoder`.
.. versionadded:: 0.3.0 | 4.963445 | 5.518512 | 0.899417 |
r
raise NotImplementedError(
'Concreate subclasses of {0.__module__}.{0.__qualname__} have to '
'override .set() method'.format(CachePolicy)
) | def set(self, key: CacheKey, value: Optional[CacheValue]) -> None | r"""Create or update a cache.
:param key: A key string to create or update.
:type key: :const:`CacheKey`
:param value: A value to cache. :const:`None` to remove cache.
:type value: :class:`~typing.Optional`\ [:const:`CacheValue`] | 13.98773 | 14.239081 | 0.982348 |
r
if not (isinstance(key, type(self)) and
key.type is EntityType.property):
return []
claims_map = self.attributes.get('claims') or {}
assert isinstance(claims_map, collections.abc.Mapping)
claims = claims_map.get(key.id, [])
claims.sort(key=la... | def getlist(self, key: 'Entity') -> Sequence[object] | r"""Return all values associated to the given ``key`` property
in sequence.
:param key: The property entity.
:type key: :class:`Entity`
:return: A sequence of all values associated to the given ``key``
property. It can be empty if nothing is associated to
... | 4.8874 | 5.166436 | 0.945991 |
if self.data is None:
guessed_type = self.client.guess_entity_type(self.id)
if guessed_type is not None:
return guessed_type
# If guessing was failed follow the straightforward way.
return EntityType(self.attributes['type']) | def type(self) -> EntityType | (:class:`EntityType`) The type of entity, :attr:`~EntityType.item`
or :attr:`~EntityType.property`.
.. versionadded:: 0.2.0 | 7.0457 | 6.918102 | 1.018444 |
return db.Table('fp_user_role',
db.Column(
'user_id', db.Integer, db.ForeignKey('{}.{}'.format(
table_name, id_column_name))),
db.Column(
'role_id', db.Integer, db.ForeignKey('fp_role... | def make_user_role_table(table_name='user', id_column_name='id') | Create the user-role association table so that
it correctly references your own UserMixin subclass. | 3.187827 | 3.081484 | 1.03451 |
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
from .models import Ability
desired_ability = Ability.query.filter_by(
name=ability).first()
user_abilities = []
current_user = get_user()
for role in current_... | def user_has(ability, get_user=import_user) | Takes an ability (a string name of either a role or an ability) and returns the function if the user has that ability | 2.56515 | 2.536319 | 1.011367 |
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
from .models import Role
current_user = get_user()
if role in current_user.roles:
return func(*args, **kwargs)
raise Forbidden("You do not have access")
return inn... | def user_is(role, get_user=import_user) | Takes an role (a string name of either a role or an ability) and returns the function if the user has that role | 2.517125 | 2.659299 | 0.946537 |
joinfile = path
sourcefiles = msettings['JOINED'][path]
# Generate the combo file as a string.
combo_data, dirname = combine_files(joinfile, sourcefiles, client)
if path.endswith('.css'):
mime_type = 'text/css'
elif joinfile.endswith('.js'):
mime_type = 'application/jav... | def combo_serve(request, path, client) | Handles generating a 'combo' file for the given path. This is similar to
what happens when we upload to S3. Processors are applied, and we get
the value that we would if we were serving from S3. This is a good way
to make sure combo files work as intended before rolling out
to production. | 6.317479 | 6.274817 | 1.006799 |
if path.endswith('.css'):
media_path_prefix = msettings['CSS_PATH']
elif path.endswith('.js'):
media_path_prefix = msettings['JS_PATH']
else:
# This isn't a CSS/JS file, no combo for you.
return None
if media_path_prefix:
# CS/JSS path prefix has been set. F... | def _form_key_str(path) | Given a URL path, massage it into a key we can perform a lookup on the
MEDIASYNC['JOINED'] dict with.
This mostly involves figuring into account the CSS_PATH and JS_PATH
settings, if they have been set. | 5.667518 | 4.596047 | 1.233129 |
key_str = _form_key_str(path)
if not key_str:
# _form_key_str() says this isn't even a CSS/JS file.
return None
if not msettings['JOINED'].has_key(key_str):
# No combo file match found. Must be an single file.
return None
else:
# Combo match found, return th... | def _find_combo_match(path) | Calculate the key to check the MEDIASYNC['JOINED'] dict for, perform the
lookup, and return the matching key string if a match is found. If no
match is found, return None instead. | 8.90791 | 6.327734 | 1.407757 |
if msettings['SERVE_REMOTE']:
# We're serving from S3, redirect there.
url = client.remote_media_url().strip('/') + '/%(path)s'
return redirect(url, permanent=True)
if not msettings['SERVE_REMOTE'] and msettings['EMULATE_COMBO']:
# Combo emulation is on and we're servi... | def static_serve(request, path, client) | Given a request for a media asset, this view does the necessary wrangling
to get the correct thing delivered to the user. This can also emulate the
combo behavior seen when SERVE_REMOTE == False and EMULATE_COMBO == True. | 6.522615 | 5.331512 | 1.223408 |
signal.signal(signal.SIGTERM, self._on_signal)
signal.signal(signal.SIGINT, self._on_signal)
xheaders = self.application.settings.get('xheaders', False)
max_body_size = self.application.settings.get('max_body_size', None)
max_buffer_size = self.application.settings.get('... | def start_server(self, port_number, number_of_procs=0) | Create a HTTP server and start it.
:param int port_number: the port number to bind the server to
:param int number_of_procs: number of processes to pass to
Tornado's ``httpserver.HTTPServer.start``.
If the application's ``debug`` setting is ``True``, then we are
going to ru... | 2.091657 | 1.810984 | 1.154983 |
self.start_server(port_number, number_of_procs)
iol = ioloop.IOLoop.instance()
try:
self.application.start(iol)
except Exception:
self.logger.exception('application terminated during start, '
'exiting')
sys.e... | def run(self, port_number, number_of_procs=0) | Create the server and run the IOLoop.
:param int port_number: the port number to bind the server to
:param int number_of_procs: number of processes to pass to
Tornado's ``httpserver.HTTPServer.start``.
If the application's ``debug`` setting is ``True``, then we are
going to... | 4.895334 | 5.999287 | 0.815986 |
def decorator(func):
if isinstance(func, property):
func = func.fget
func.short_description = description
return func
return decorator | def short_description(description) | Sets 'short_description' attribute (this attribute is in exports to generate header name). | 3.415429 | 3.749866 | 0.910814 |
'''
Adds configuration parameters from a Python module.
'''
for key, value in module.__dict__.iteritems():
if key[0:2] != '__':
self.__setattr__(attr=key, value=value) | def add_module(self, module) | Adds configuration parameters from a Python module. | 5.922741 | 3.627025 | 1.632948 |
resolved_url = reverse('IS:login')
login_url_parts = list(urlparse(resolved_url))
if redirect_field_name:
querystring = QueryDict(login_url_parts[4], mutable=True)
querystring[redirect_field_name] = next
login_url_parts[4] = querystring.urlencode(safe='/')
raise HTTPRedire... | def redirect_to_login(next, redirect_field_name=REDIRECT_FIELD_NAME) | Redirects the user to the login page, passing the given 'next' page | 3.232475 | 3.341008 | 0.967515 |
def redirect_or_exception(ex):
if not self.request.user or not self.request.user.is_authenticated:
if self.auto_login_redirect:
redirect_to_login(self.request.get_full_path())
else:
raise HTTPUnauthorizedResponseExcepti... | def _check_permission(self, name, obj=None) | If customer is not authorized he should not get information that object is exists.
Therefore 403 is returned if object was not found or is redirected to the login page.
If custmer is authorized and object was not found is returned 404.
If object was found and user is not authorized is returned 4... | 3.461991 | 3.36456 | 1.028958 |
self.fig = pyplot.figure()
self.plot()
self.axes = pyplot.gca()
self.save_plot(self.fig, self.axes, **kwargs)
pyplot.close(self.fig) | def plot_and_save(self, **kwargs) | Used when the plot method defined does not create a figure nor calls save_plot
Then the plot method has to use self.fig | 3.062442 | 2.456331 | 1.246755 |
# Data #
counts = [sum(map(len, b.contigs)) for b in self.parent.bins]
# Linear bins in logarithmic space #
if 'log' in kwargs.get('x_scale', ''):
start, stop = numpy.log10(1), numpy.log10(max(counts))
bins = list(numpy.logspace(start=start, stop=stop, nu... | def plot(self, bins=250, **kwargs) | An example plot function. You have to subclass this method. | 3.678934 | 3.704672 | 0.993052 |
from matplotlib import animation
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=360, interval=20)
FFMpegWriter = animation.writers['ffmpeg']
writer = FFMpegWriter(bitrate= bitrate, fps=fps)
# Save #
self.avi_path = self.base_dir + self.short_... | def save_anim(self, fig, animate, init, bitrate=10000, fps=30) | Not functional -- TODO | 3.084419 | 2.97457 | 1.036929 |
if 'SLURM_NTASKS' in os.environ: return int(os.environ['SLURM_NTASKS'])
elif 'SLURM_JOB_CPUS_PER_NODE' in os.environ:
text = os.environ['SLURM_JOB_CPUS_PER_NODE']
if is_integer(text): return int(text)
else:
n, N = re.findall("([1-9]+)\(x([1-9]+)\)", text)[0]
... | def count_processors() | How many cores does the current computer have ? | 2.679788 | 2.591786 | 1.033954 |
if os.environ.get('CSCSERVICE') == 'sisu': return "sisu"
elif os.environ.get('SLURM_JOB_PARTITION') == 'halvan': return "halvan"
elif os.environ.get('SNIC_RESOURCE') == 'milou': return "milou"
elif os.environ.get('LAPTOP') == 'macbook_air': return... | def guess_server_name() | We often use the same servers, which one are we running on now ? | 6.08896 | 5.865252 | 1.038141 |
if isinstance(instance_or_pk, cls):
if instance_or_pk in cls._flask_signalbus_sa.session:
return instance_or_pk
instance_or_pk = inspect(cls).primary_key_from_instance(instance_or_pk)
return cls.query.get(instance_or_pk) | def get_instance(cls, instance_or_pk) | Return a model instance in ``db.session``.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
Example::
@db.atomic
def increase_account_balance(account, amount):
# Here `Acco... | 4.196352 | 4.275839 | 0.98141 |
mapper = inspect(cls)
pk_attrs = [mapper.get_property_by_column(c).class_attribute for c in mapper.primary_key]
pk_values = cls.get_pk_values(instance_or_pk)
clause = and_(*[attr == value for attr, value in zip(pk_attrs, pk_values)])
return cls.query.filter(clause).with... | def lock_instance(cls, instance_or_pk, read=False) | Return a locked model instance in ``db.session``.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple.
:param read: If `True`, a reading lock is obtained instead of
a writing lock. | 2.772903 | 2.663922 | 1.04091 |
if isinstance(instance_or_pk, cls):
cls._flask_signalbus_sa.session.flush()
instance_or_pk = inspect(cls).primary_key_from_instance(instance_or_pk)
return instance_or_pk if isinstance(instance_or_pk, tuple) else (instance_or_pk,) | def get_pk_values(cls, instance_or_pk) | Return a primary key as a tuple.
:param instance_or_pk: An instance of this model class, or a
primary key. A composite primary key can be passed as a
tuple. | 4.343194 | 4.330724 | 1.002879 |
@wraps(func)
def wrapper(*args, **kwargs):
session = self.session
session_info = session.info
if session_info.get(_ATOMIC_FLAG_SESSION_INFO_KEY):
return func(*args, **kwargs)
f = retry_on_deadlock(session)(func)
sessio... | def atomic(self, func) | A decorator that wraps a function in an atomic block.
Example::
db = CustomSQLAlchemy()
@db.atomic
def f():
write_to_db('a message')
return 'OK'
assert f() == 'OK'
This code defines the function ``f``, which is wrapped in an
... | 2.531651 | 2.411867 | 1.049664 |
session = self.session
assert session.info.get(_ATOMIC_FLAG_SESSION_INFO_KEY), \
'Calls to "retry_on_integrity_error" must be wrapped in atomic block.'
session.flush()
try:
yield
session.flush()
except IntegrityError:
rais... | def retry_on_integrity_error(self) | Re-raise :class:`~sqlalchemy.exc.IntegrityError` as `DBSerializationError`.
This is mainly useful to handle race conditions in atomic
blocks. For example, even if prior to a database INSERT we
have verified that there is no existing row with the given
primary key, we still may get an
... | 9.369537 | 6.854902 | 1.366838 |
# If we are in a site with one language there is no need of saving translations
if site_is_monolingual():
return False
cls = sender
# If its class has no "translatable_fields" then there are no translations
if not hasattr(cls._meta, "translatable_fields"):
return False
# For each translatable field, ge... | def _save_translations(sender, instance, *args, **kwargs) | This signal saves model translations. | 4.715559 | 4.655104 | 1.012987 |
# Basic filtering: filter translations by module, model an object_id
_filter = {"module": instance.__module__, "model": instance.__class__.__name__, "object_id": instance.id}
if lang:
_filter["lang"] = lang
# If we specify a field we get ONE translation (this field translation)
if field:
_filter["field"] ... | def _get_fieldtranslations(instance, field=None, lang=None) | Get all the translations for this object. | 3.897684 | 3.609936 | 1.07971 |
# Gets field translations
translations = _get_fieldtranslations(instance=instance, lang=lang)
for translation_i in translations:
# Sets translated field lang for this language
field_lang = trans_attr(translation_i.field, translation_i.lang)
setattr(instance, field_lang, translation_i.translation)
# Sets is... | def _load_translations(instance, lang=None) | Loads all translations as dynamic attributes:
<attr>_<lang_code>
<attr>_<lang_code>_is_fuzzy | 3.979709 | 3.857495 | 1.031682 |
# If class has no translatable fields get out
if not hasattr(instance._meta, "translatable_fields"):
return False
# If we are in a site with one language there is no need of saving translations
if site_is_monolingual():
return False
# Translatable fields
translatable_fields = instance._meta.translatable_... | def _set_dict_translations(instance, dict_translations) | Establece los atributos de traducciones a partir de una dict que
contiene todas las traducciones. | 3.426651 | 3.325609 | 1.030383 |
# 1. Execute _save_translations when saving an object
signals.post_save.connect(_save_translations, sender=sender)
# 2. Adds get_fieldtranslations to class. Remember that this method get all the translations.
sender.add_to_class("get_fieldtranslations", _get_fieldtranslations)
# 3. Adss load_translations. Rememb... | def add_translation(sender) | Adds the actions to a class. | 5.795258 | 5.652076 | 1.025333 |
key = key_generators.key_from_file(filename, passphrase)
inline_transform(filename, key)
return key | def encrypt_file_inline(filename, passphrase) | Encrypt file inline, with an optional passphrase.
If you set the passphrase to None, a default is used.
This will make you vulnerable to confirmation attacks
and learn-partial-information attacks.
:param filename: The name of the file to encrypt.
:type filename: str
:param passphrase: The pass... | 11.527493 | 21.062283 | 0.547305 |
pos = 0
for chunk, fp in iter_transform(filename, key):
fp.seek(pos)
fp.write(chunk)
fp.flush()
pos = fp.tell() | def inline_transform(filename, key) | Encrypt file inline.
Encrypts a given file with the given key,
and replaces it directly without any extra
space requirement.
:param filename: The name of the file to encrypt.
:type filename: str
:param key: The key used to encrypt the file.
:type key: str | 4.423985 | 5.326443 | 0.83057 |
# We are not specifying the IV here.
aes = AES.new(key, AES.MODE_CTR, counter=Counter.new(128))
with open(filename, 'rb+') as f:
for chunk in iter(lambda: f.read(CHUNK_SIZE), b''):
yield aes.encrypt(chunk), f | def iter_transform(filename, key) | Generate encrypted file with given key.
This generator function reads the file
in chunks and encrypts them using AES-CTR,
with the specified key.
:param filename: The name of the file to encrypt.
:type filename: str
:param key: The key used to encrypt the file.
:type key: str
:returns:... | 3.430358 | 3.97971 | 0.861962 |
assert isinstance(permission, BasePermission), 'Only permission instances can be added to the set'
self._permissions[name] = permission | def set(self, name, permission) | Adds permission with the given name to the set. Permission with the same name will be overridden.
Args:
name: name of the permission
permission: permission instance | 7.306159 | 6.005182 | 1.216642 |
if not widget:
widget = self.field.widget
if self.field.localize:
widget.is_localized = True
attrs = attrs or {}
attrs = self.build_widget_attrs(attrs, widget)
auto_id = self.auto_id
if auto_id and 'id' not in attrs and 'id' not in widge... | def as_widget(self, widget=None, attrs=None, only_initial=False) | Renders the field by rendering the passed widget, adding any HTML
attributes passed as attrs. If no widget is specified, then the
field's default widget will be used. | 2.678615 | 2.604363 | 1.028511 |
def create_schema_class(m):
if hasattr(m, 'send_signalbus_message'):
# Signal models should not use the SQLAlchemy session.
class Meta(object):
model = m
else:
class Meta(object):
model = m
sqla_session = sessi... | def _setup_schema(Base, session) | Create a function which adds `__marshmallow__` attribute to all signal models. | 3.556057 | 3.223539 | 1.103153 |
try:
signalbus = self.__signalbus
except AttributeError:
signalbus = self.__signalbus = SignalBus(self, init_app=False)
return signalbus | def signalbus(self) | The associated `SignalBus` object. | 4.470964 | 4.091961 | 1.092621 |
base = self.db.Model
return [
cls for cls in base._decl_class_registry.values() if (
isinstance(cls, type)
and issubclass(cls, base)
and hasattr(cls, 'send_signalbus_message')
)
] | def get_signal_models(self) | Return all signal types in a list.
:rtype: list(`signal-model`) | 5.334015 | 5.083963 | 1.049184 |
models_to_flush = self.get_signal_models() if models is None else models
pks_to_flush = {}
try:
for model in models_to_flush:
_raise_error_if_not_signal_model(model)
m = inspect(model)
pk_attrs = [m.get_property_by_column(c).c... | def flush(self, models=None, wait=3.0) | Send all pending signals over the message bus.
:param models: If passed, flushes only signals of the specified types.
:type models: list(`signal-model`) or `None`
:param float wait: The number of seconds the method will wait
after obtaining the list of pending signals, to allow
... | 3.553585 | 3.7582 | 0.945555 |
models_to_flush = self.get_signal_models()
try:
return sum(self._flushmany_signals(model) for model in models_to_flush)
finally:
self.signal_session.remove() | def flushmany(self) | Send a potentially huge number of pending signals over the message bus.
This method assumes that the number of pending signals might
be huge, so that they might not fit into memory. However,
`SignalBus.flushmany` is not very smart in handling concurrent
senders. It is mostly useful when... | 7.262953 | 7.130356 | 1.018596 |
status_code = int(status_code)
if status_code >= 400:
kwargs = {'status_code': status_code}
if self.get_query_argument('reason', None):
kwargs['reason'] = self.get_query_argument('reason')
if self.get_query_argument('log_message', None):
... | def get(self, status_code) | Returns the requested status.
:param int status_code: the status code to return
:queryparam str reason: optional reason phrase | 1.875442 | 2.168144 | 0.864999 |
self.init_config(app)
self.iiif_ext = IIIF(app=app)
self.iiif_ext.api_decorator_handler(protect_api)
self.iiif_ext.uuid_to_image_opener_handler(image_opener)
app.extensions['invenio-iiif'] = self | def init_app(self, app) | Flask application initialization. | 5.89354 | 5.75423 | 1.02421 |
super(InvenioIIIFAPI, self).init_app(app)
api = Api(app=app)
self.iiif_ext.init_restful(api, prefix=app.config['IIIF_API_PREFIX']) | def init_app(self, app) | Flask application initialization. | 8.041405 | 7.423972 | 1.083167 |
'''
Returns the absolute path of the ``path`` argument.
If ``path`` is already absolute, nothing changes. If the ``path`` is
relative, then the BASEDIR will be prepended.
'''
if os.path.isabs(path):
return path
else:
return os.path.abspath... | def get_absolute_path(self, path) | Returns the absolute path of the ``path`` argument.
If ``path`` is already absolute, nothing changes. If the ``path`` is
relative, then the BASEDIR will be prepended. | 3.519395 | 1.771822 | 1.986314 |
'''
Returns all absolute paths to the roles/ directories, while considering
the ``BASEDIR`` and ``ROLES`` config variables.
'''
roles = []
for path in self.config.ROLES:
roles.append(self.get_absolute_path(path))
return roles | def get_roles_paths(self) | Returns all absolute paths to the roles/ directories, while considering
the ``BASEDIR`` and ``ROLES`` config variables. | 8.404933 | 2.985702 | 2.815061 |
'''
Returns a key-value dict with a roles, while the key is the role name
and the value is the absolute role path.
'''
roles = {}
paths = self.get_roles_paths()
for path in paths:
for entry in os.listdir(path):
rolepath = os.path.join(... | def get_roles(self) | Returns a key-value dict with a roles, while the key is the role name
and the value is the absolute role path. | 3.935689 | 2.012836 | 1.955295 |
'''
Reads and parses a YAML file and returns the content.
'''
with open(filename, 'r') as f:
d = re.sub(r'\{\{ *([^ ]+) *\}\}', r'\1', f.read())
y = yaml.safe_load(d)
return y if y else {} | def read_yaml(self, filename) | Reads and parses a YAML file and returns the content. | 4.041614 | 3.375178 | 1.197452 |
'''
Loops through the dir_path and parses all YAML files inside the
directory.
If no param is defined, then all YAML items will be returned
in a list. If a param is defined, then all items will be scanned for
this param and a list of all those values will be returned.
... | def get_yaml_items(self, dir_path, param=None) | Loops through the dir_path and parses all YAML files inside the
directory.
If no param is defined, then all YAML items will be returned
in a list. If a param is defined, then all items will be scanned for
this param and a list of all those values will be returned. | 2.877274 | 1.642356 | 1.751919 |
response = re.sub("^['\"]", "", response)
response = re.sub("['\"]$", "", response)
return response | def clean_response(response) | Cleans string quoting in response. | 3.730326 | 2.917815 | 1.278465 |
def decorator(action):
@wraps(action)
def f(*args, **kwargs):
num_failures = 0
while True:
try:
return action(*args, **kwargs)
except (DBAPIError, DBSerializationError) as e:
num_failures ... | def retry_on_deadlock(session, retries=6, min_wait=0.1, max_wait=10.0) | Return function decorator that executes the function again in case of a deadlock. | 2.85394 | 2.727949 | 1.046185 |
def memoized(*args, **kwargs):
if hasattr(memoized, '__cache__'):
return memoized.__cache__
result = f(*args, **kwargs)
memoized.__cache__ = result
return result
return memoized | def cached(f) | Decorator for functions evaluated only once. | 2.255699 | 2.322316 | 0.971314 |
# Called when you access the property #
def retrieve_from_cache(self):
# Is it in the cache ? #
if '__cache__' not in self.__dict__: self.__cache__ = {}
if f.__name__ in self.__cache__: return self.__cache__[f.__name__]
# Where should we look in the file system ? #
i... | def property_pickled(f) | Same thing as above but the result will be stored on disk
The path of the pickle file will be determined by looking for the
`cache_dir` attribute of the instance containing the cached property.
If no `cache_dir` attribute exists the `p` attribute will be accessed with
the name of the property being cach... | 2.576038 | 2.391144 | 1.077325 |
if max_num is None:
max_num = DEFAULT_MAX_NUM
# hard limit on forms instantiated, to prevent memory-exhaustion attacks
# limit is simply max_num + DEFAULT_MAX_NUM (which is 2*DEFAULT_MAX_NUM
# if max_num is None in the first place)
absolute_max = max_num + DEFAULT_MAX_NUM
if min_num... | def smartformset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
can_delete=False, min_num=None, max_num=None, validate_min=False, validate_max=False) | Return a FormSet for the given form class. | 2.867546 | 2.870195 | 0.999077 |
obj = form.save(commit=False)
change = obj.pk is not None
self.save_obj(obj, form, change)
if hasattr(form, 'save_m2m'):
form.save_m2m()
return obj | def save_form(self, form, **kwargs) | Contains formset save, prepare obj for saving | 3.260074 | 2.873632 | 1.134479 |
return (
super().get_method_returning_field_value(field_name)
or self.core.get_method_returning_field_value(field_name)
) | def get_method_returning_field_value(self, field_name) | Field values can be obtained from view or core. | 2.869831 | 2.346927 | 1.222804 |
if pk:
obj = get_object_or_none(self.core.model, pk=pk)
else:
try:
obj = self.get_obj(False)
except Http404:
obj = get_object_or_none(self.core.model, **self.get_obj_filters())
if not obj:
raise Http404
... | def _get_perm_obj_or_404(self, pk=None) | If is send parameter pk is returned object according this pk,
else is returned object from get_obj method, but it search only inside filtered values for current user,
finally if object is still None is returned according the input key from all objects.
If object does not exist is raised Http404 | 2.738943 | 2.780325 | 0.985116 |
# Is there any filter?
if request.method == "POST":
data = request.POST.dict()
if not data["search"] or data["search"]=="":
return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(data["language"],data["filter"])))
return HttpResponseRedirect(reverse("modeltranslation:view_all_url",arg... | def view_all(request, language, filter=None) | View all translations that are in site. | 2.598408 | 2.568024 | 1.011832 |
translation = get_object_or_404(FieldTranslation, id=translation)
if request.method == 'POST':
if "cancel" in request.POST:
return HttpResponseRedirect(reverse("modeltranslation:view_all_url",args=(translation.lang,"all")))
elif "save" in request.POST:
form = FieldTranslationForm(request.POST, instance=tr... | def edit(request, translation) | Edit a translation.
@param request: Django HttpRequest object.
@param translation: Translation id
@return Django HttpResponse object with the view or a redirection. | 2.319405 | 2.403146 | 0.965154 |
FieldTranslation.delete_orphan_translations()
translations = FieldTranslation.objects.filter(lang=language)
for trans in translations:
trans.source_text = trans.source_text.replace("'","\'").replace("\"","\\\"")
trans.translation = trans.translation.replace("'","\'").replace("\"","\\\"")
replacements = {"tran... | def export_translations(request, language) | Export translations view. | 2.55945 | 2.532843 | 1.010505 |
FieldTranslation.delete_orphan_translations()
num_translations = FieldTranslation.update_translations()
return render_to_response('modeltranslation/admin/update_translations_ok.html',{"num_translations":num_translations}, RequestContext(request)) | def update_translations(request) | Update translations: delete orphan translations and creates empty translations for new objects in database. | 4.591321 | 3.942574 | 1.164549 |
response = requests.get(self.make_url(url), headers=self.headers)
if not response.ok:
raise Exception(
'{status}: {reason}.\nCircleCI Status NOT OK'.format(
status=response.status_code, reason=response.reason))
return response.json() | def client_get(self, url, **kwargs) | Send GET request with given url. | 4.349511 | 4.123025 | 1.054932 |
response = requests.post(self.make_url(url),
data=json.dumps(kwargs),
headers=self.headers)
if not response.ok:
raise Exception(
'{status}: {reason}.\nCircleCI Status NOT OK'.format(
... | def client_post(self, url, **kwargs) | Send POST request with given url and keyword args. | 3.897891 | 3.752354 | 1.038786 |
response = requests.delete(self.make_url(url), headers=self.headers)
if not response.ok:
raise Exception(
'{status}: {reason}.\nCircleCI Status NOT OK'.format(
status=response.status_code, reason=response.reason))
return response.json() | def client_delete(self, url, **kwargs) | Send POST request with given url. | 4.443644 | 4.225159 | 1.05171 |
method = 'GET'
url = '/projects?circle-token={token}'.format(
token=self.client.api_token)
json_data = self.client.request(method, url)
return json_data | def list_projects(self) | Return a list of all followed projects. | 5.329303 | 4.533621 | 1.175507 |
method = 'POST'
url = ('/project/{username}/{project}/tree/{branch}?'
'circle-token={token}'.format(
username=username, project=project,
branch=branch, token=self.client.api_token))
if build_params is not None:
json_data ... | def trigger(self, username, project, branch, **build_params) | Trigger new build and return a summary of the build. | 2.969065 | 2.95177 | 1.005859 |
method = 'POST'
url = ('/project/{username}/{project}/{build_num}/cancel?'
'circle-token={token}'.format(username=username,
project=project,
build_num=build_num,
... | def cancel(self, username, project, build_num) | Cancel the build and return its summary. | 2.983801 | 2.96957 | 1.004792 |
method = 'GET'
url = ('/recent-builds?circle-token={token}&limit={limit}&'
'offset={offset}'.format(token=self.client.api_token,
limit=limit,
offset=offset))
json_data = self.client.request(me... | def recent_all_projects(self, limit=30, offset=0) | Return information about recent builds across all projects.
Args:
limit (int), Number of builds to return, max=100, defaults=30.
offset (int): Builds returned from this point, default=0.
Returns:
A list of dictionaries. | 3.540967 | 3.741166 | 0.946488 |
method = 'GET'
if branch is not None:
url = ('/project/{username}/{project}/tree/{branch}?'
'circle-token={token}&limit={limit}&offset={offset}&filter={status_filter}'.format(
username=username, project=project, branch=branch,
... | def recent(self, username, project, limit=1, offset=0, branch=None, status_filter="") | Return status of recent builds for given project.
Retrieves build statuses for given project and branch. If branch is
None it retrieves most recent build.
Args:
username (str): Name of the user.
project (str): Name of the project.
limit (int): Number of b... | 1.851259 | 1.933708 | 0.957363 |
method = 'DELETE'
url = ('/project/{username}/{project}/build-cache?'
'circle-token={token}'.format(username=username,
project=project,
token=self.client.api_token))
json_data = self... | def clear(self, username, project) | Clear the cache for given project. | 4.04583 | 3.751152 | 1.078557 |
data = request.data.copy()
# Get chat type record
try:
ct = ChatType.objects.get(pk=data.pop("chat_type"))
data["chat_type"] = ct
except ChatType.DoesNotExist:
return typeNotFound404
if not self.is_path_unique(
None, data... | def post(self, request, format=None) | Add a new Channel. | 3.826432 | 3.551504 | 1.077412 |
data = request.data.copy()
# Get chat type record
try:
ct = ChatType.objects.get(id=data.pop("chat_type"))
data["chat_type"] = ct
except ChatType.DoesNotExist:
return typeNotFound404
if not self.is_path_unique(
data["id"]... | def patch(self, request, format=None) | Update an existing Channel | 3.59445 | 3.393687 | 1.059158 |
h = hashlib.sha256()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(CHUNK_SIZE), b''):
h.update(chunk)
return h.hexdigest() | def sha256_file(path) | Calculate sha256 hex digest of a file.
:param path: The path of the file you are calculating the digest of.
:type path: str
:returns: The sha256 hex digest of the specified file.
:rtype: builtin_function_or_method | 1.800294 | 2.169467 | 0.829832 |
hexdigest = sha256_file(filename)
if passphrase is None:
passphrase = DEFAULT_HMAC_PASSPHRASE
return keyed_hash(hexdigest, passphrase) | def key_from_file(filename, passphrase) | Calculate convergent encryption key.
This takes a filename and an optional passphrase.
If no passphrase is given, a default is used.
Using the default passphrase means you will be
vulnerable to confirmation attacks and
learn-partial-information attacks.
:param filename: The filename you want t... | 5.334094 | 8.009563 | 0.665966 |
encodedPassphrase = passphrase.encode()
encodedDigest = digest.encode()
return hmac.new(encodedPassphrase, encodedDigest, hashlib.sha256).digest() | def keyed_hash(digest, passphrase) | Calculate a HMAC/keyed hash.
:param digest: Digest used to create hash.
:type digest: str
:param passphrase: Passphrase used to generate the hash.
:type passphrase: str
:returns: HMAC/keyed hash.
:rtype: str | 3.161037 | 4.082245 | 0.774338 |
_assert_valid_sexpr(sexpr)
for child in sexpr[1:]:
if _is_sexpr(child) and child[0] in tags:
return child
return None | def find_child(sexpr: Sexpr, *tags: str) -> Optional[Sexpr] | Search for a tag among direct children of the s-expression. | 2.877285 | 2.776565 | 1.036275 |
"Helper function for building an attribute dictionary."
self.attrs = self.widget.build_attrs(*args, **kwargs)
return self.attrs | def build_attrs(self, *args, **kwargs) | Helper function for building an attribute dictionary. | 6.442758 | 3.98463 | 1.616902 |
return {
'initial': os.path.basename(conditional_escape(value)),
'initial_url': conditional_escape(value.url),
} | def get_template_substitution_values(self, value) | Return value-related substitutions. | 7.240537 | 6.675428 | 1.084655 |
return (
not hasattr(self.choices, 'queryset') or
self.choices.queryset.count() > settings.FOREIGN_KEY_MAX_SELECBOX_ENTRIES
) | def is_restricted(self) | Returns True or False according to number of objects in queryset.
If queryset contains too much objects the widget will be restricted and won't be used select box with choices. | 10.940514 | 6.345279 | 1.724197 |
info = find_info(name)
os.environ['OPEN311_CITY_INFO'] = dumps(info)
return Three(**info) | def city(name=None) | Store the city that will be queried against.
>>> three.city('sf') | 14.817231 | 17.119297 | 0.865528 |
kwargs['endpoint'] = endpoint
os.environ['OPEN311_CITY_INFO'] = dumps(kwargs)
return Three(**kwargs) | def dev(endpoint, **kwargs) | Use an endpoint and any additional keyword arguments rather than one
of the pre-defined cities. Similar to the `city` function, but useful for
development. | 16.828238 | 16.351126 | 1.029179 |
field_names = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
field_names += flatten_fieldsets(opts.get('fieldsets'))
else:
for field in opts.get('fields', ()):
if isinstance(field, (list, tuple)):
field_names.extend(fie... | def flatten_fieldsets(fieldsets) | Returns a list of field names from an admin fieldsets structure. | 2.242878 | 1.982406 | 1.131392 |
inline_views = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
inline_views += get_inline_views_from_fieldsets(opts.get('fieldsets'))
elif 'inline_view' in opts:
inline_views.append(opts.get('inline_view'))
return inline_views | def get_inline_views_from_fieldsets(fieldsets) | Returns a list of field names from an admin fieldsets structure. | 2.126199 | 2.075598 | 1.024379 |
inline_views = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
inline_views += get_inline_views_opts_from_fieldsets(opts.get('fieldsets'))
elif 'inline_view' in opts:
inline_views.append(opts)
return inline_views | def get_inline_views_opts_from_fieldsets(fieldsets) | Returns a list of field names from an admin fieldsets structure. | 2.192889 | 2.285833 | 0.959339 |
fun_kwargs = fun_kwargs or {}
if view:
view_readonly_data = _get_view_readonly_data(field_name, view, fun_kwargs)
if view_readonly_data is not None:
return view_readonly_data
field_data = _get_model_readonly_data(field_name, instance, fun_kwargs)
if field_data is not N... | def get_readonly_field_data(field_name, instance, view=None, fun_kwargs=None) | Returns field humanized value, label and widget which are used to display of instance or view readonly data.
Args:
field_name: name of the field which will be displayed
instance: model instance
view: view instance
fun_kwargs: kwargs that can be used inside method call
Returns:
... | 2.227312 | 2.32172 | 0.959337 |
from is_core.forms.utils import ReadonlyValue
value, _, _ = get_readonly_field_data(field_name, obj)
return display_for_value(value.humanized_value if isinstance(value, ReadonlyValue) else value, request=request) | def display_object_data(obj, field_name, request=None) | Returns humanized value of model object that can be rendered to HTML or returned as part of REST
examples:
boolean True/Talse ==> Yes/No
objects ==> object display name with link if current user has permissions to see the object
field with choices ==> string value of choice
field with h... | 7.45111 | 9.235495 | 0.806791 |
from is_core.utils.compatibility import admin_display_for_value
if request and isinstance(value, Model):
return render_model_object_with_link(request, value)
else:
return (
(value and ugettext('Yes') or ugettext('No')) if isinstance(value, bool) else admin_display_for_value... | def display_for_value(value, request=None) | Converts humanized value
examples:
boolean True/Talse ==> Yes/No
objects ==> object display name with link if current user has permissions to see the object
datetime ==> in localized format | 5.038207 | 4.985167 | 1.01064 |
from is_core.site import get_model_core
model_core = get_model_core(obj.__class__)
if model_core and hasattr(model_core, 'ui_patterns'):
edit_pattern = model_core.ui_patterns.get('detail')
return (
edit_pattern.get_url_string(request, obj=obj)
if edit_pattern an... | def get_url_from_model_core(request, obj) | Returns object URL from model core. | 3.608188 | 3.530831 | 1.021909 |
if (is_callable(getattr(obj, 'get_absolute_url', None)) and
(not hasattr(obj, 'can_see_edit_link') or
(is_callable(getattr(obj, 'can_see_edit_link', None)) and obj.can_see_edit_link(request)))):
return call_method_with_unknown_input(obj.get_absolute_url, request=request)
el... | def get_obj_url(request, obj) | Returns object URL if current logged user has permissions to see the object | 3.4196 | 3.346692 | 1.021785 |
from is_core.patterns import reverse_pattern
pattern = reverse_pattern(pattern_name)
assert pattern is not None, 'Invalid pattern name {}'.format(pattern_name)
if pattern.has_permission('get', request, view_kwargs=view_kwargs):
return pattern.get_url_string(request, view_kwargs=view_kwarg... | def get_link_or_none(pattern_name, request, view_kwargs=None) | Helper that generate URL prom pattern name and kwargs and check if current request has permission to open the URL.
If not None is returned.
Args:
pattern_name (str): slug which is used for view registratin to pattern
request (django.http.request.HttpRequest): Django request object
view_... | 3.749431 | 4.025354 | 0.931454 |
method = getattr(self, field_name, None)
return method if method and callable(method) else None | def get_method_returning_field_value(self, field_name) | Method should return object method that can be used to get field value.
Args:
field_name: name of the field
Returns: method for obtaining a field value | 4.054037 | 5.263498 | 0.770217 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.