sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def permissions(cls, instance, db_session=None):
"""
returns all non-resource permissions based on what groups user
belongs and directly set ones for this user
:param instance:
:param db_session:
:return:
"""
db_session = get_db_session(db_session, in... | returns all non-resource permissions based on what groups user
belongs and directly set ones for this user
:param instance:
:param db_session:
:return: | entailment |
def resources_with_perms(
cls, instance, perms, resource_ids=None, resource_types=None, db_session=None
):
"""
returns all resources that user has perms for
(note that at least one perm needs to be met)
:param instance:
:param perms:
:param resource_ids: ... | returns all resources that user has perms for
(note that at least one perm needs to be met)
:param instance:
:param perms:
:param resource_ids: restricts the search to specific resources
:param resource_types:
:param db_session:
:return: | entailment |
def groups_with_resources(cls, instance):
"""
Returns a list of groups users belongs to with eager loaded
resources owned by those groups
:param instance:
:return:
"""
return instance.groups_dynamic.options(
sa.orm.eagerload(cls.models_proxy.Group.res... | Returns a list of groups users belongs to with eager loaded
resources owned by those groups
:param instance:
:return: | entailment |
def resources_with_possible_perms(
cls, instance, resource_ids=None, resource_types=None, db_session=None
):
"""
returns list of permissions and resources for this user
:param instance:
:param resource_ids: restricts the search to specific resources
:param resource_t... | returns list of permissions and resources for this user
:param instance:
:param resource_ids: restricts the search to specific resources
:param resource_types: restricts the search to specific resource types
:param db_session:
:return: | entailment |
def gravatar_url(cls, instance, default="mm", **kwargs):
"""
returns user gravatar url
:param instance:
:param default:
:param kwargs:
:return:
"""
# construct the url
hash = hashlib.md5(instance.email.encode("utf8").lower()).hexdigest()
i... | returns user gravatar url
:param instance:
:param default:
:param kwargs:
:return: | entailment |
def set_password(cls, instance, raw_password):
"""
sets new password on a user using password manager
:param instance:
:param raw_password:
:return:
"""
# support API for both passlib 1.x and 2.x
hash_callable = getattr(
instance.passwordmanag... | sets new password on a user using password manager
:param instance:
:param raw_password:
:return: | entailment |
def check_password(cls, instance, raw_password, enable_hash_migration=True):
"""
checks string with users password hash using password manager
:param instance:
:param raw_password:
:param enable_hash_migration: if legacy hashes should be migrated
:return:
"""
... | checks string with users password hash using password manager
:param instance:
:param raw_password:
:param enable_hash_migration: if legacy hashes should be migrated
:return: | entailment |
def by_id(cls, user_id, db_session=None):
"""
fetch user by user id
:param user_id:
:param db_session:
:return:
"""
db_session = get_db_session(db_session)
query = db_session.query(cls.model)
query = query.filter(cls.model.id == user_id)
q... | fetch user by user id
:param user_id:
:param db_session:
:return: | entailment |
def by_user_name_and_security_code(cls, user_name, security_code, db_session=None):
"""
fetch user objects by user name and security code
:param user_name:
:param security_code:
:param db_session:
:return:
"""
db_session = get_db_session(db_session)
... | fetch user objects by user name and security code
:param user_name:
:param security_code:
:param db_session:
:return: | entailment |
def by_user_names(cls, user_names, db_session=None):
"""
fetch user objects by user names
:param user_names:
:param db_session:
:return:
"""
user_names = [(name or "").lower() for name in user_names]
db_session = get_db_session(db_session)
query =... | fetch user objects by user names
:param user_names:
:param db_session:
:return: | entailment |
def user_names_like(cls, user_name, db_session=None):
"""
fetch users with similar names using LIKE clause
:param user_name:
:param db_session:
:return:
"""
db_session = get_db_session(db_session)
query = db_session.query(cls.model)
query = query.... | fetch users with similar names using LIKE clause
:param user_name:
:param db_session:
:return: | entailment |
def by_email(cls, email, db_session=None):
"""
fetch user object by email
:param email:
:param db_session:
:return:
"""
db_session = get_db_session(db_session)
query = db_session.query(cls.model).filter(
sa.func.lower(cls.model.email) == (emai... | fetch user object by email
:param email:
:param db_session:
:return: | entailment |
def users_for_perms(cls, perm_names, db_session=None):
"""
return users hat have one of given permissions
:param perm_names:
:param db_session:
:return:
"""
db_session = get_db_session(db_session)
query = db_session.query(cls.model)
query = query.... | return users hat have one of given permissions
:param perm_names:
:param db_session:
:return: | entailment |
def handle_joined(self, connection, event):
"""
Store join times for current nicknames when we first join.
"""
nicknames = [s.lstrip("@+") for s in event.arguments()[-1].split()]
for nickname in nicknames:
self.joined[nickname] = datetime.now() | Store join times for current nicknames when we first join. | entailment |
def handle_join(self, connection, event):
"""
Store join time for a nickname when it joins.
"""
nickname = self.get_nickname(event)
self.joined[nickname] = datetime.now() | Store join time for a nickname when it joins. | entailment |
def handle_quit(self, connection, event):
"""
Store quit time for a nickname when it quits.
"""
nickname = self.get_nickname(event)
self.quit[nickname] = datetime.now()
del self.joined[nickname] | Store quit time for a nickname when it quits. | entailment |
def timesince(self, when):
"""
Returns human friendly version of the timespan between now
and the given datetime.
"""
units = (
("year", 60 * 60 * 24 * 365),
("week", 60 * 60 * 24 * 7),
("day", 60 * 60 * 24),
("hour", 60 * ... | Returns human friendly version of the timespan between now
and the given datetime. | entailment |
def version(self, event):
"""
Shows version information.
"""
name = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
return "%s [%s]" % (settings.GNOTTY_VERSION_STRING, name) | Shows version information. | entailment |
def commands(self, event):
"""
Lists all available commands.
"""
commands = sorted(self.commands_dict().keys())
return "Available commands: %s" % " ".join(commands) | Lists all available commands. | entailment |
def help(self, event, command_name=None):
"""
Shows the help message for the bot. Takes an optional command name
which when given, will show help for that command.
"""
if command_name is None:
return ("Type !commands for a list of all commands. Type "
... | Shows the help message for the bot. Takes an optional command name
which when given, will show help for that command. | entailment |
def uptime(self, event, nickname=None):
"""
Shows the amount of time since the given nickname has been
in the channel. If no nickname is given, I'll use my own.
"""
if nickname and nickname != self.nickname:
try:
uptime = self.timesince(self.joined[nic... | Shows the amount of time since the given nickname has been
in the channel. If no nickname is given, I'll use my own. | entailment |
def seen(self, event, nickname):
"""
Shows the amount of time since the given nickname was last
seen in the channel.
"""
try:
self.joined[nickname]
except KeyError:
pass
else:
if nickname == self.get_nickname(event):
... | Shows the amount of time since the given nickname was last
seen in the channel. | entailment |
def id(self):
""" Unique identifier of user object"""
return sa.Column(sa.Integer, primary_key=True, autoincrement=True) | Unique identifier of user object | entailment |
def last_login_date(self):
""" Date of user's last login """
return sa.Column(
sa.TIMESTAMP(timezone=False),
default=lambda x: datetime.utcnow(),
server_default=sa.func.now(),
) | Date of user's last login | entailment |
def security_code_date(self):
""" Date of user's security code update """
return sa.Column(
sa.TIMESTAMP(timezone=False),
default=datetime(2000, 1, 1),
server_default="2000-01-01 01:01",
) | Date of user's security code update | entailment |
def groups_dynamic(self):
""" returns dynamic relationship for groups - allowing for
filtering of data """
return sa.orm.relationship(
"Group",
secondary="users_groups",
lazy="dynamic",
passive_deletes=True,
passive_updates=True,
... | returns dynamic relationship for groups - allowing for
filtering of data | entailment |
def resources(self):
""" Returns all resources directly owned by user, can be used to assign
ownership of new resources::
user.resources.append(resource) """
return sa.orm.relationship(
"Resource",
cascade="all",
passive_deletes=True,
... | Returns all resources directly owned by user, can be used to assign
ownership of new resources::
user.resources.append(resource) | entailment |
def resources_dynamic(self):
""" Returns all resources directly owned by group, can be used to assign
ownership of new resources::
user.resources.append(resource) """
return sa.orm.relationship(
"Resource",
cascade="all",
passive_deletes=True,
... | Returns all resources directly owned by group, can be used to assign
ownership of new resources::
user.resources.append(resource) | entailment |
def validate_permission(self, key, permission):
""" validates if group can get assigned with permission"""
if permission.perm_name not in self.__possible_permissions__:
raise AssertionError(
"perm_name is not one of {}".format(self.__possible_permissions__)
)
... | validates if group can get assigned with permission | entailment |
def parse_feeds(self, message_channel=True):
"""
Iterates through each of the feed URLs, parses their items, and
sends any items to the channel that have not been previously
been parsed.
"""
if parse:
for feed_url in self.feeds:
feed = parse(fe... | Iterates through each of the feed URLs, parses their items, and
sends any items to the channel that have not been previously
been parsed. | entailment |
def ChunkBy(self: dict, f=None):
"""
[
{
'self': [1, 1, 3, 3, 1, 1],
'f': lambda x: x%2,
'assert': lambda ret: ret == [[1, 1], [3, 3], [1, 1]]
}
]
"""
if f is None:
return _chunk(self.items())
if is_to_destruct(f):
f = destruct... | [
{
'self': [1, 1, 3, 3, 1, 1],
'f': lambda x: x%2,
'assert': lambda ret: ret == [[1, 1], [3, 3], [1, 1]]
}
] | entailment |
def GroupBy(self: dict, f=None):
"""
[
{
'self': [1, 2, 3],
'f': lambda x: x%2,
'assert': lambda ret: ret[0] == [2] and ret[1] == [1, 3]
}
]
"""
if f and is_to_destruct(f):
f = destruct_func(f)
return _group_by(self.items(), f) | [
{
'self': [1, 2, 3],
'f': lambda x: x%2,
'assert': lambda ret: ret[0] == [2] and ret[1] == [1, 3]
}
] | entailment |
def Take(self: dict, n):
"""
[
{
'self': [1, 2, 3],
'n': 2,
'assert': lambda ret: list(ret) == [1, 2]
}
]
"""
for i, e in enumerate(self.items()):
if i == n:
break
yield e | [
{
'self': [1, 2, 3],
'n': 2,
'assert': lambda ret: list(ret) == [1, 2]
}
] | entailment |
def TakeIf(self: dict, f):
"""
[
{
'self': [1, 2, 3],
'f': lambda e: e%2,
'assert': lambda ret: list(ret) == [1, 3]
}
]
"""
if is_to_destruct(f):
f = destruct_func(f)
return (e for e in self.items() if f(e)) | [
{
'self': [1, 2, 3],
'f': lambda e: e%2,
'assert': lambda ret: list(ret) == [1, 3]
}
] | entailment |
def TakeWhile(self: dict, f):
"""
[
{
'self': [1, 2, 3, 4, 5],
'f': lambda x: x < 4,
'assert': lambda ret: list(ret) == [1, 2, 3]
}
]
"""
if is_to_destruct(f):
f = destruct_func(f)
for e in self.items():
if not f(e):
... | [
{
'self': [1, 2, 3, 4, 5],
'f': lambda x: x < 4,
'assert': lambda ret: list(ret) == [1, 2, 3]
}
] | entailment |
def Drop(self: dict, n):
"""
[
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [1, 2]
}
]
"""
n = len(self) - n
if n <= 0:
yield from self.items()
else:
for i, e in enumerate(self.items()):
... | [
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [1, 2]
}
] | entailment |
def Skip(self: dict, n):
"""
[
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [4, 5]
}
]
"""
con = self.items()
for i, _ in enumerate(con):
if i == n:
break
return... | [
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [4, 5]
}
] | entailment |
def print_meter_record(file_path, rows=5):
""" Output readings for specified number of rows to console """
m = nr.read_nem_file(file_path)
print('Header:', m.header)
print('Transactions:', m.transactions)
for nmi in m.readings:
for channel in m.readings[nmi]:
print(nmi, 'Channel'... | Output readings for specified number of rows to console | entailment |
def users(self):
""" returns all users that have permissions for this resource"""
return sa.orm.relationship(
"User",
secondary="users_resources_permissions",
passive_deletes=True,
passive_updates=True,
) | returns all users that have permissions for this resource | entailment |
def from_resource_deeper(
cls, resource_id=None, limit_depth=1000000, db_session=None, *args, **kwargs
):
"""
This returns you subtree of ordered objects relative
to the start resource_id (currently only implemented in postgresql)
:param resource_id:
:param limit_dep... | This returns you subtree of ordered objects relative
to the start resource_id (currently only implemented in postgresql)
:param resource_id:
:param limit_depth:
:param db_session:
:return: | entailment |
def delete_branch(cls, resource_id=None, db_session=None, *args, **kwargs):
"""
This deletes whole branch with children starting from resource_id
:param resource_id:
:param db_session:
:return:
"""
tablename = cls.model.__table__.name
# lets lock rows to... | This deletes whole branch with children starting from resource_id
:param resource_id:
:param db_session:
:return: | entailment |
def from_parent_deeper(
cls, parent_id=None, limit_depth=1000000, db_session=None, *args, **kwargs
):
"""
This returns you subtree of ordered objects relative
to the start parent_id (currently only implemented in postgresql)
:param resource_id:
:param limit_depth:
... | This returns you subtree of ordered objects relative
to the start parent_id (currently only implemented in postgresql)
:param resource_id:
:param limit_depth:
:param db_session:
:return: | entailment |
def build_subtree_strut(self, result, *args, **kwargs):
"""
Returns a dictionary in form of
{node:Resource, children:{node_id: Resource}}
:param result:
:return:
"""
items = list(result)
root_elem = {"node": None, "children": OrderedDict()}
if len... | Returns a dictionary in form of
{node:Resource, children:{node_id: Resource}}
:param result:
:return: | entailment |
def path_upper(
cls, object_id, limit_depth=1000000, db_session=None, *args, **kwargs
):
"""
This returns you path to root node starting from object_id
currently only for postgresql
:param object_id:
:param limit_depth:
:param db_session:
:return:... | This returns you path to root node starting from object_id
currently only for postgresql
:param object_id:
:param limit_depth:
:param db_session:
:return: | entailment |
def move_to_position(
cls,
resource_id,
to_position,
new_parent_id=noop,
db_session=None,
*args,
**kwargs
):
"""
Moves node to new location in the tree
:param resource_id: resource to move
:param to_position: new position
... | Moves node to new location in the tree
:param resource_id: resource to move
:param to_position: new position
:param new_parent_id: new parent id
:param db_session:
:return: | entailment |
def shift_ordering_up(cls, parent_id, position, db_session=None, *args, **kwargs):
"""
Shifts ordering to "open a gap" for node insertion,
begins the shift from given position
:param parent_id:
:param position:
:param db_session:
:return:
"""
db_s... | Shifts ordering to "open a gap" for node insertion,
begins the shift from given position
:param parent_id:
:param position:
:param db_session:
:return: | entailment |
def set_position(cls, resource_id, to_position, db_session=None, *args, **kwargs):
"""
Sets node position for new node in the tree
:param resource_id: resource to move
:param to_position: new position
:param db_session:
:return:def count_children(cls, resource_id, db_ses... | Sets node position for new node in the tree
:param resource_id: resource to move
:param to_position: new position
:param db_session:
:return:def count_children(cls, resource_id, db_session=None): | entailment |
def check_node_parent(
cls, resource_id, new_parent_id, db_session=None, *args, **kwargs
):
"""
Checks if parent destination is valid for node
:param resource_id:
:param new_parent_id:
:param db_session:
:return:
"""
db_session = get_db_sessio... | Checks if parent destination is valid for node
:param resource_id:
:param new_parent_id:
:param db_session:
:return: | entailment |
def count_children(cls, resource_id, db_session=None, *args, **kwargs):
"""
Counts children of resource node
:param resource_id:
:param db_session:
:return:
"""
query = db_session.query(cls.model.resource_id)
query = query.filter(cls.model.parent_id == re... | Counts children of resource node
:param resource_id:
:param db_session:
:return: | entailment |
def check_node_position(
cls, parent_id, position, on_same_branch, db_session=None, *args, **kwargs
):
"""
Checks if node position for given parent is valid, raises exception if
this is not the case
:param parent_id:
:param position:
:param on_same_branch: in... | Checks if node position for given parent is valid, raises exception if
this is not the case
:param parent_id:
:param position:
:param on_same_branch: indicates that we are checking same branch
:param db_session:
:return: | entailment |
def egcd(b, n):
'''
Given two integers (b, n), returns (gcd(b, n), a, m) such that
a*b + n*m = gcd(b, n).
Adapted from several sources:
https://brilliant.org/wiki/extended-euclidean-algorithm/
https://rosettacode.org/wiki/Modular_inverse
https://en.wikibooks.org/wiki/Algorithm_Imp... | Given two integers (b, n), returns (gcd(b, n), a, m) such that
a*b + n*m = gcd(b, n).
Adapted from several sources:
https://brilliant.org/wiki/extended-euclidean-algorithm/
https://rosettacode.org/wiki/Modular_inverse
https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Exte... | entailment |
def register(linter):
"""Add the needed transformations and supressions.
"""
linter.register_checker(MongoEngineChecker(linter))
add_transform('mongoengine')
add_transform('mongomotor')
suppress_qs_decorator_messages(linter)
suppress_fields_attrs_messages(linter) | Add the needed transformations and supressions. | entailment |
def output_as_csv(file_name, nmi=None, output_file=None):
"""
Transpose all channels and output a csv that is easier
to read and do charting on
:param file_name: The NEM file to process
:param nmi: Which NMI to output if more than one
:param output_file: Specify different output location
:r... | Transpose all channels and output a csv that is easier
to read and do charting on
:param file_name: The NEM file to process
:param nmi: Which NMI to output if more than one
:param output_file: Specify different output location
:returns: The file that was created | entailment |
def get(cls, group_id, db_session=None):
"""
Fetch row using primary key -
will use existing object in session if already present
:param group_id:
:param db_session:
:return:
"""
db_session = get_db_session(db_session)
return db_session.query(cls.... | Fetch row using primary key -
will use existing object in session if already present
:param group_id:
:param db_session:
:return: | entailment |
def by_group_name(cls, group_name, db_session=None):
"""
fetch group by name
:param group_name:
:param db_session:
:return:
"""
db_session = get_db_session(db_session)
query = db_session.query(cls.model).filter(cls.model.group_name == group_name)
... | fetch group by name
:param group_name:
:param db_session:
:return: | entailment |
def get_user_paginator(
cls,
instance,
page=1,
item_count=None,
items_per_page=50,
user_ids=None,
GET_params=None,
):
"""
returns paginator over users belonging to the group
:param instance:
:param page:
:param item_cou... | returns paginator over users belonging to the group
:param instance:
:param page:
:param item_count:
:param items_per_page:
:param user_ids:
:param GET_params:
:return: | entailment |
def resources_with_possible_perms(
cls,
instance,
perm_names=None,
resource_ids=None,
resource_types=None,
db_session=None,
):
"""
returns list of permissions and resources for this group,
resource_ids restricts the search to specific resou... | returns list of permissions and resources for this group,
resource_ids restricts the search to specific resources
:param instance:
:param perm_names:
:param resource_ids:
:param resource_types:
:param db_session:
:return: | entailment |
def create_pool(
database,
minsize=1,
maxsize=10,
echo=False,
loop=None,
**kwargs
):
"""
创建支持上下文管理的pool
"""
coro = _create_pool(
database=database,
minsize=minsize,
maxsize=maxsize,
echo=echo,
loop=loop,
**kw... | 创建支持上下文管理的pool | entailment |
def wait_closed(self):
"""
Wait for closing all pool's connections.
"""
if self._closed:
return
if not self._closing:
raise RuntimeError(
".wait_closed() should be called "
"after .close()"
)
while self.... | Wait for closing all pool's connections. | entailment |
def sync_close(self):
"""
同步关闭
"""
if self._closed:
return
while self._free:
conn = self._free.popleft()
if not conn.closed:
# pragma: no cover
conn.sync_close()
for conn in self._used:
if not... | 同步关闭 | entailment |
def _fill_free_pool(self, override_min):
"""
iterate over free connections and remove timeouted ones
"""
while self.size < self.minsize:
self._acquiring += 1
try:
conn = yield from connect(
database=self._database,
... | iterate over free connections and remove timeouted ones | entailment |
def add_function(self, function):
"""
Adds the function to the list of registered functions.
"""
function = self.build_function(function)
if function.name in self.functions:
raise FunctionAlreadyRegistered(function.name)
self.functions[function.name] = functio... | Adds the function to the list of registered functions. | entailment |
def get_one(self, context, name):
"""
Returns a function if it is registered, the context is ignored.
"""
try:
return self.functions[name]
except KeyError:
raise FunctionNotFound(name) | Returns a function if it is registered, the context is ignored. | entailment |
def subfield_get(self, obj, type=None):
"""
Verbatim copy from:
https://github.com/django/django/blob/1.9.13/django/db/models/fields/subclassing.py#L38
"""
if obj is None:
return self
return obj.__dict__[self.field.name] | Verbatim copy from:
https://github.com/django/django/blob/1.9.13/django/db/models/fields/subclassing.py#L38 | entailment |
def _preprocess_kwargs(self, initial_kwargs):
""" Replace generic key related attribute with filters by object_id and content_type fields """
kwargs = initial_kwargs.copy()
generic_key_related_kwargs = self._get_generic_key_related_kwargs(initial_kwargs)
for key, value in generic_key_rel... | Replace generic key related attribute with filters by object_id and content_type fields | entailment |
def categorize(
data, col_name: str = None, new_col_name: str = None,
categories: dict = None, max_categories: float = 0.15
):
"""
:param data:
:param col_name:
:param new_col_name:
:param categories:
:param max_categories: max proportion threshold of categories
:return: new categori... | :param data:
:param col_name:
:param new_col_name:
:param categories:
:param max_categories: max proportion threshold of categories
:return: new categories
:rtype dict: | entailment |
def dropna(data: pd.DataFrame, axis: int, **params):
"""
Remove columns with more NA values than threshold level
:param data:
:param axis:
Axes are defined for arrays with more than one dimension.
A 2-dimensional array has two corresponding axes: the first running
vertically downwards... | Remove columns with more NA values than threshold level
:param data:
:param axis:
Axes are defined for arrays with more than one dimension.
A 2-dimensional array has two corresponding axes: the first running
vertically downwards across rows (axis 0), and the second running
horizontally ... | entailment |
def dropna_columns(data: pd.DataFrame, max_na_values: int=0.15):
"""
Remove columns with more NA values than threshold level
:param data:
:param max_na_values: proportion threshold of max na values
:return:
"""
size = data.shape[0]
df_na = (data.isnull().sum()/size) >= max_na_values
... | Remove columns with more NA values than threshold level
:param data:
:param max_na_values: proportion threshold of max na values
:return: | entailment |
def dropna_rows(data: pd.DataFrame, columns_name: str=None):
"""
Remove columns with more NA values than threshold level
:param data:
:param columns_name:
:return:
"""
params = {}
if columns_name is not None:
params.update({'subset': columns_name.split(',')})
data.dropna(in... | Remove columns with more NA values than threshold level
:param data:
:param columns_name:
:return: | entailment |
def drop_columns_with_unique_values(
data: pd.DataFrame, max_unique_values: int = 0.25
):
"""
Remove columns when the proportion
of the total of unique values is more than the max_unique_values
threshold, just for columns with type as object or category
:param data:
:param max_unique_values... | Remove columns when the proportion
of the total of unique values is more than the max_unique_values
threshold, just for columns with type as object or category
:param data:
:param max_unique_values:
:return: | entailment |
def list(self, request, *args, **kwargs):
"""
To get an actual value for object quotas limit and usage issue a **GET** request against */api/<objects>/*.
To get all quotas visible to the user issue a **GET** request against */api/quotas/*
"""
return super(QuotaViewSet, self).lis... | To get an actual value for object quotas limit and usage issue a **GET** request against */api/<objects>/*.
To get all quotas visible to the user issue a **GET** request against */api/quotas/* | entailment |
def retrieve(self, request, *args, **kwargs):
"""
To set quota limit issue a **PUT** request against */api/quotas/<quota uuid>** with limit values.
Please note that if a quota is a cache of a backend quota (e.g. 'storage' size of an OpenStack tenant),
it will be impossible to modify it ... | To set quota limit issue a **PUT** request against */api/quotas/<quota uuid>** with limit values.
Please note that if a quota is a cache of a backend quota (e.g. 'storage' size of an OpenStack tenant),
it will be impossible to modify it through */api/quotas/<quota uuid>** endpoint.
Example of ... | entailment |
def history(self, request, uuid=None):
"""
Historical data endpoints could be available for any objects (currently
implemented for quotas and events count). The data is available at *<object_endpoint>/history/*,
for example: */api/quotas/<uuid>/history/*.
There are two ways to d... | Historical data endpoints could be available for any objects (currently
implemented for quotas and events count). The data is available at *<object_endpoint>/history/*,
for example: */api/quotas/<uuid>/history/*.
There are two ways to define datetime points for historical data.
1. Send... | entailment |
def _get_url(self, obj):
"""
Gets object url
"""
format_kwargs = {
'app_label': obj._meta.app_label,
}
try:
format_kwargs['model_name'] = getattr(obj.__class__, 'get_url_name')()
except AttributeError:
format_kwargs['model_name'... | Gets object url | entailment |
def to_representation(self, obj):
"""
Serializes any object to his url representation
"""
kwargs = None
for field in self.lookup_fields:
if hasattr(obj, field):
kwargs = {field: getattr(obj, field)}
break
if kwargs is None:
... | Serializes any object to his url representation | entailment |
def to_internal_value(self, data):
"""
Restores model instance from its url
"""
if not data:
return None
request = self._get_request()
user = request.user
try:
obj = core_utils.instance_from_url(data, user=user)
model = obj.__cl... | Restores model instance from its url | entailment |
def validate(self, data):
"""
Check that the start is before the end.
"""
if 'start' in data and 'end' in data and data['start'] >= data['end']:
raise serializers.ValidationError(_('End must occur after start.'))
return data | Check that the start is before the end. | entailment |
def send_task(app_label, task_name):
""" A helper function to deal with waldur_core "high-level" tasks.
Define high-level task with explicit name using a pattern:
waldur_core.<app_label>.<task_name>
.. code-block:: python
@shared_task(name='waldur_core.openstack.provision_instan... | A helper function to deal with waldur_core "high-level" tasks.
Define high-level task with explicit name using a pattern:
waldur_core.<app_label>.<task_name>
.. code-block:: python
@shared_task(name='waldur_core.openstack.provision_instance')
def provision_instance_fn(in... | entailment |
def log_celery_task(request):
""" Add description to celery log output """
task = request.task
description = None
if isinstance(task, Task):
try:
description = task.get_description(*request.args, **request.kwargs)
except NotImplementedError:
pass
except Ex... | Add description to celery log output | entailment |
def run(self, serialized_instance, *args, **kwargs):
""" Deserialize input data and start backend operation execution """
try:
instance = utils.deserialize_instance(serialized_instance)
except ObjectDoesNotExist:
message = ('Cannot restore instance from serialized object ... | Deserialize input data and start backend operation execution | entailment |
def is_previous_task_processing(self, *args, **kwargs):
""" Return True if exist task that is equal to current and is uncompleted """
app = self._get_app()
inspect = app.control.inspect()
active = inspect.active() or {}
scheduled = inspect.scheduled() or {}
reserved = ins... | Return True if exist task that is equal to current and is uncompleted | entailment |
def apply_async(self, args=None, kwargs=None, **options):
""" Do not run background task if previous task is uncompleted """
if self.is_previous_task_processing(*args, **kwargs):
message = 'Background task %s was not scheduled, because its predecessor is not completed yet.' % self.name
... | Do not run background task if previous task is uncompleted | entailment |
def _get_cache_key(self, args, kwargs):
""" Returns key to be used in cache """
hash_input = json.dumps({'name': self.name, 'args': args, 'kwargs': kwargs}, sort_keys=True)
# md5 is used for internal caching, not need to care about security
return hashlib.md5(hash_input).hexdigest() | Returns key to be used in cache | entailment |
def apply_async(self, args=None, kwargs=None, **options):
"""
Checks whether task must be skipped and decreases the counter in that case.
"""
key = self._get_cache_key(args, kwargs)
counter, penalty = cache.get(key, (0, 0))
if not counter:
return super(Penaliz... | Checks whether task must be skipped and decreases the counter in that case. | entailment |
def on_failure(self, exc, task_id, args, kwargs, einfo):
"""
Increases penalty for the task and resets the counter.
"""
key = self._get_cache_key(args, kwargs)
_, penalty = cache.get(key, (0, 0))
if penalty < self.MAX_PENALTY:
penalty += 1
logger.debu... | Increases penalty for the task and resets the counter. | entailment |
def on_success(self, retval, task_id, args, kwargs):
"""
Clears cache for the task.
"""
key = self._get_cache_key(args, kwargs)
if cache.get(key) is not None:
cache.delete(key)
logger.debug('Penalty for the task %s has been removed.' % self.name)
... | Clears cache for the task. | entailment |
def log_backend_action(action=None):
""" Logging for backend method.
Expects django model instance as first argument.
"""
def decorator(func):
@functools.wraps(func)
def wrapped(self, instance, *args, **kwargs):
action_name = func.func_name.replace('_', ' ') if action is Non... | Logging for backend method.
Expects django model instance as first argument. | entailment |
def get_services(cls, request=None):
""" Get a list of services endpoints.
{
"Oracle": "/api/oracle/",
"OpenStack": "/api/openstack/",
"GitLab": "/api/gitlab/",
"DigitalOcean": "/api/digitalocean/"
}
"""
retu... | Get a list of services endpoints.
{
"Oracle": "/api/oracle/",
"OpenStack": "/api/openstack/",
"GitLab": "/api/gitlab/",
"DigitalOcean": "/api/digitalocean/"
} | entailment |
def get_resources(cls, request=None):
""" Get a list of resources endpoints.
{
"DigitalOcean.Droplet": "/api/digitalocean-droplets/",
"Oracle.Database": "/api/oracle-databases/",
"GitLab.Group": "/api/gitlab-groups/",
"GitLab.Project": ... | Get a list of resources endpoints.
{
"DigitalOcean.Droplet": "/api/digitalocean-droplets/",
"Oracle.Database": "/api/oracle-databases/",
"GitLab.Group": "/api/gitlab-groups/",
"GitLab.Project": "/api/gitlab-projects/"
} | entailment |
def get_services_with_resources(cls, request=None):
""" Get a list of services and resources endpoints.
{
...
"GitLab": {
"url": "/api/gitlab/",
"service_project_link_url": "/api/gitlab-service-project-link/",
... | Get a list of services and resources endpoints.
{
...
"GitLab": {
"url": "/api/gitlab/",
"service_project_link_url": "/api/gitlab-service-project-link/",
"resources": {
"Project": "/api/gitlab... | entailment |
def get_service_models(cls):
""" Get a list of service models.
{
...
'gitlab': {
"service": nodeconductor_gitlab.models.GitLabService,
"service_project_link": nodeconductor_gitlab.models.GitLabServiceProjectLink,
... | Get a list of service models.
{
...
'gitlab': {
"service": nodeconductor_gitlab.models.GitLabService,
"service_project_link": nodeconductor_gitlab.models.GitLabServiceProjectLink,
"resources": [
... | entailment |
def get_resource_models(cls):
""" Get a list of resource models.
{
'DigitalOcean.Droplet': waldur_digitalocean.models.Droplet,
'JIRA.Project': waldur_jira.models.Project,
'OpenStack.Tenant': waldur_openstack.models.Tenant
}
"""
... | Get a list of resource models.
{
'DigitalOcean.Droplet': waldur_digitalocean.models.Droplet,
'JIRA.Project': waldur_jira.models.Project,
'OpenStack.Tenant': waldur_openstack.models.Tenant
} | entailment |
def get_service_resources(cls, model):
""" Get resource models by service model """
key = cls.get_model_key(model)
return cls.get_service_name_resources(key) | Get resource models by service model | entailment |
def get_service_name_resources(cls, service_name):
""" Get resource models by service name """
from django.apps import apps
resources = cls._registry[service_name]['resources'].keys()
return [apps.get_model(resource) for resource in resources] | Get resource models by service name | entailment |
def get_name_for_model(cls, model):
""" Get a name for given class or model:
-- it's a service type for a service
-- it's a <service_type>.<resource_model_name> for a resource
"""
key = cls.get_model_key(model)
model_str = cls._get_model_str(model)
service... | Get a name for given class or model:
-- it's a service type for a service
-- it's a <service_type>.<resource_model_name> for a resource | entailment |
def get_related_models(cls, model):
""" Get a dictionary with related structure models for given class or model:
>> SupportedServices.get_related_models(gitlab_models.Project)
{
'service': nodeconductor_gitlab.models.GitLabService,
'service_project_link':... | Get a dictionary with related structure models for given class or model:
>> SupportedServices.get_related_models(gitlab_models.Project)
{
'service': nodeconductor_gitlab.models.GitLabService,
'service_project_link': nodeconductor_gitlab.models.GitLabServiceProjec... | entailment |
def _is_active_model(cls, model):
""" Check is model app name is in list of INSTALLED_APPS """
# We need to use such tricky way to check because of inconsistent apps names:
# some apps are included in format "<module_name>.<app_name>" like "waldur_core.openstack"
# other apps are include... | Check is model app name is in list of INSTALLED_APPS | entailment |
def process(self, event):
""" Send events as push notification via Google Cloud Messaging.
Expected settings as follows:
# https://developers.google.com/mobile/add
WALDUR_CORE['GOOGLE_API'] = {
'NOTIFICATION_TITLE': "Waldur notification",
... | Send events as push notification via Google Cloud Messaging.
Expected settings as follows:
# https://developers.google.com/mobile/add
WALDUR_CORE['GOOGLE_API'] = {
'NOTIFICATION_TITLE': "Waldur notification",
'Android': {
... | entailment |
def get_context_data_from_headers(request, headers_schema):
"""
Extracts context data from request headers according to specified schema.
>>> from lxml import etree as et
>>> from datetime import date
>>> from pyws.functions.args import TypeFactory
>>> Fake = type('Fake', (object, ), {})
>>... | Extracts context data from request headers according to specified schema.
>>> from lxml import etree as et
>>> from datetime import date
>>> from pyws.functions.args import TypeFactory
>>> Fake = type('Fake', (object, ), {})
>>> request = Fake()
>>> request.parsed_data = Fake()
>>> request.... | entailment |
def lazy_constant(fn):
"""Decorator to make a function that takes no arguments use the LazyConstant class."""
class NewLazyConstant(LazyConstant):
@functools.wraps(fn)
def __call__(self):
return self.get_value()
return NewLazyConstant(fn) | Decorator to make a function that takes no arguments use the LazyConstant class. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.