text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_call2custom_manager(node):
"""Checks if the call is being done to a custom queryset manager.""" |
called = safe_infer(node.func)
funcdef = getattr(called, '_proxied', None)
return _is_custom_qs_manager(funcdef) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_custom_manager_attribute(node):
"""Checks if the attribute is a valid attribute for a queryset manager. """ |
attrname = node.attrname
if not name_is_from_qs(attrname):
return False
for attr in node.get_children():
inferred = safe_infer(attr)
funcdef = getattr(inferred, '_proxied', None)
if _is_custom_qs_manager(funcdef):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def by_group_and_perm(cls, group_id, perm_name, db_session=None):
""" return by by_user_and_perm and permission name :param group_id: :param perm_name: :param db... |
db_session = get_db_session(db_session)
query = db_session.query(cls.model).filter(cls.model.group_id == group_id)
query = query.filter(cls.model.perm_name == perm_name)
return query.first() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serve_forever(django=False):
""" Starts the gevent-socketio server. """ |
logger = getLogger("irc.dispatch")
logger.setLevel(settings.LOG_LEVEL)
logger.addHandler(StreamHandler())
app = IRCApplication(django)
server = SocketIOServer((settings.HTTP_HOST, settings.HTTP_PORT), app)
print "%s [Bot: %s] listening on %s:%s" % (
settings.GNOTTY_VERSION_STRING,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kill(pid_file):
""" Attempts to shut down a previously started daemon. """ |
try:
with open(pid_file) as f:
os.kill(int(f.read()), 9)
os.remove(pid_file)
except (IOError, OSError):
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run():
""" CLI entry point. Parses args and starts the gevent-socketio server. """ |
settings.parse_args()
pid_name = "gnotty-%s-%s.pid" % (settings.HTTP_HOST, settings.HTTP_PORT)
pid_file = settings.PID_FILE or os.path.join(gettempdir(), pid_name)
if settings.KILL:
if kill(pid_file):
print "Daemon killed"
else:
print "Could not kill any daemons"... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_start(self, host, port, channel, nickname, password):
""" A WebSocket session has started - create a greenlet to host the IRC client, and start it. """ |
self.client = WebSocketIRCClient(host, port, channel, nickname,
password, self)
self.spawn(self.client.start) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disconnect(self, *args, **kwargs):
""" WebSocket was disconnected - leave the IRC channel. """ |
quit_message = "%s %s" % (settings.GNOTTY_VERSION_STRING,
settings.GNOTTY_PROJECT_URL)
self.client.connection.quit(quit_message)
super(IRCNamespace, self).disconnect(*args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def respond_webhook(self, environ):
""" Passes the request onto a bot with a webhook if the webhook path is requested. """ |
request = FieldStorage(fp=environ["wsgi.input"], environ=environ)
url = environ["PATH_INFO"]
params = dict([(k, request[k].value) for k in request])
try:
if self.bot is None:
raise NotImplementedError
response = self.bot.handle_webhook_event(envir... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def respond_static(self, environ):
""" Serves a static file when Django isn't being used. """ |
path = os.path.normpath(environ["PATH_INFO"])
if path == "/":
content = self.index()
content_type = "text/html"
else:
path = os.path.join(os.path.dirname(__file__), path.lstrip("/"))
try:
with open(path, "r") as f:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def index(self):
""" Loads the chat interface template when Django isn't being used, manually dealing with the Django template bits. """ |
root_dir = os.path.dirname(__file__)
template_dir = os.path.join(root_dir, "templates", "gnotty")
with open(os.path.join(template_dir, "base.html"), "r") as f:
base = f.read()
with open(os.path.join(template_dir, "chat.html"), "r") as f:
base = base.replace("{% b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authorized(self, environ):
""" If we're running Django and ``GNOTTY_LOGIN_REQUIRED`` is set to ``True``, pull the session cookie from the environment and val... |
if self.django and settings.LOGIN_REQUIRED:
try:
from django.conf import settings as django_settings
from django.contrib.auth import SESSION_KEY
from django.contrib.auth.models import User
from django.contrib.sessions.models import Ses... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def base_query(cls, db_session=None):
""" returns base query for specific service :param db_session: :return: query """ |
db_session = get_db_session(db_session)
return db_session.query(cls.model) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on(event, *args, **kwargs):
""" Event method wrapper for bot mixins. When a bot is constructed, its metaclass inspects all members of all base classes, and l... |
def wrapper(func):
for i, arg in args:
kwargs[i] = arg
func.event = Event(event, kwargs)
return func
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_dict(self, exclude_keys=None, include_keys=None):
""" return dictionary of keys and values corresponding to this model's data - if include_keys is null t... |
d = {}
exclude_keys_list = exclude_keys or []
include_keys_list = include_keys or []
for k in self._get_keys():
if k not in exclude_keys_list and (
k in include_keys_list or not include_keys
):
d[k] = getattr(self, k)
retur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_appstruct(self):
""" return list of tuples keys and values corresponding to this model's data """ |
result = []
for k in self._get_keys():
result.append((k, getattr(self, k)))
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, db_session=None):
""" Deletes the object via session, this will permanently delete the object from storage on commit :param db_session: :return:... |
db_session = get_db_session(db_session, self)
db_session.delete(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def power_up(self):
""" power up the HX711 :return: always True :rtype bool """ |
GPIO.output(self._pd_sck, False)
time.sleep(0.01)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset(self):
""" reset the HX711 and prepare it for the next reading :return: True on success :rtype bool :raises GenericHX711Exception """ |
logging.debug("power down")
self.power_down()
logging.debug("power up")
self.power_up()
logging.debug("read some raw data")
result = self.get_raw_data(6)
if result is False:
raise GenericHX711Exception("failed to reset HX711")
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_measure_count(self, times):
""" check if "times" is within the borders defined in the class :param times: "times" to check :type times: int """ |
if not self.min_measures <= times <= self.max_measures:
raise ParameterValidationError(
"{times} is not within the borders defined in the class".format(
times=times
)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_gain_A_value(self, gain_A):
""" validate a given value for gain_A :type gain_A: int :raises: ValueError """ |
if gain_A not in self._valid_gains_for_channel_A:
raise ParameterValidationError("{gain_A} is not a valid gain".format(gain_A=gain_A)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_channel_gain(self, num):
""" Finish data transmission from HX711 by setting next required gain and channel Only called from the _read function. :type nu... |
if not 1 <= num <= 3:
raise AttributeError(
""""num" has to be in the range of 1 to 3"""
)
for _ in range(num):
logging.debug("_set_channel_gain called")
start_counter = time.perf_counter() # start timer now.
GPIO.output(self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_raw_data(self, times=5):
""" do some readings and aggregate them using the defined statistics function :param times: how many measures to aggregate :type... |
self._validate_measure_count(times)
data_list = []
while len(data_list) < times:
data = self._read()
if data not in [False, -1]:
data_list.append(data)
return data_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shift_ordering_down( self, parent_id, position, db_session=None, *args, **kwargs ):
""" Shifts ordering to "close gaps" after node deletion or being moved to... |
return self.service.shift_ordering_down(
parent_id=parent_id,
position=position,
db_session=db_session,
*args,
**kwargs
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten_list(l: List[list]) -> list: """ takes a list of lists, l and returns a flat list """ |
return [v for inner_l in l for v in inner_l] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_nem_file(file_path: str) -> NEMFile: """ Read in NEM file and return meter readings named tuple :param file_path: The NEM file to process :returns: The f... |
_, file_extension = os.path.splitext(file_path)
if file_extension.lower() == '.zip':
with zipfile.ZipFile(file_path, 'r') as archive:
for csv_file in archive.namelist():
with archive.open(csv_file) as csv_text:
# Zip file is open in binary mode
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_nem_file(nem_file) -> NEMFile: """ Parse NEM file and return meter readings named tuple """ |
reader = csv.reader(nem_file, delimiter=',')
return parse_nem_rows(reader, file_name=nem_file) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calculate_manual_reading(basic_data: BasicMeterData) -> Reading: """ Calculate the interval between two manual readings """ |
t_start = basic_data.previous_register_read_datetime
t_end = basic_data.current_register_read_datetime
read_start = basic_data.previous_register_read
read_end = basic_data.current_register_read
value = basic_data.quantity
uom = basic_data.uom
quality_method = basic_data.current_quality_met... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_interval_records(interval_record, interval_date, interval, uom, quality_method) -> List[Reading]: """ Convert interval values into tuples with datetime ... |
interval_delta = timedelta(minutes=interval)
return [
Reading(
t_start=interval_date + (i * interval_delta),
t_end=interval_date + (i * interval_delta) + interval_delta,
read_value=parse_reading(val),
uom=uom,
quality_method=quality_method,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_reading_events(readings, event_record):
""" Updates readings from a 300 row to reflect any events found in a subsequent 400 row """ |
# event intervals are 1-indexed
for i in range(event_record.start_interval - 1, event_record.end_interval):
readings[i] = Reading(
t_start=readings[i].t_start,
t_end=readings[i].t_end,
read_value=readings[i].read_value,
uom=readings[i].uom,
qu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_datetime(record: str) -> Optional[datetime]: """ Parse a datetime string into a python datetime object """ |
# NEM defines Date8, DateTime12 and DateTime14
format_strings = {8: '%Y%m%d', 12: '%Y%m%d%H%M', 14: '%Y%m%d%H%M%S'}
if record == '':
return None
return datetime.strptime(record.strip(),
format_strings[len(record.strip())]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def color(nickname):
""" Provides a consistent color for a nickname. Uses first 6 chars of nickname's md5 hash, and then slightly darkens the rgb values for use ... |
_hex = md5(nickname).hexdigest()[:6]
darken = lambda s: str(int(round(int(s, 16) * .7)))
return "rgb(%s)" % ",".join([darken(_hex[i:i+2]) for i in range(6)[::2]]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_welcome(self, connection, event):
""" Join the channel once connected to the IRC server. """ |
connection.join(self.channel, key=settings.IRC_CHANNEL_KEY or "") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_nicknameinuse(self, connection, event):
""" Increment a digit on the nickname if it's in use, and re-connect. """ |
digits = ""
while self.nickname[-1].isdigit():
digits = self.nickname[-1] + digits
self.nickname = self.nickname[:-1]
digits = 1 if not digits else int(digits) + 1
self.nickname += str(digits)
self.connect(self.host, self.port, self.nickname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def message_channel(self, message):
""" Nicer shortcut for sending a message to a channel. Also irclib doesn't handle unicode so we bypass its privmsg -> send_ra... |
data = "PRIVMSG %s :%s\r\n" % (self.channel, message)
self.connection.socket.send(data.encode("utf-8")) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emit_message(self, message):
""" Send a message to the channel. We also emit the message back to the sender's WebSocket. """ |
try:
nickname_color = self.nicknames[self.nickname]
except KeyError:
# Only accept messages if we've joined.
return
message = message[:settings.MAX_MESSAGE_LENGTH]
# Handle IRC commands.
if message.startswith("/"):
self.connection.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emit_nicknames(self):
""" Send the nickname list to the Websocket. Called whenever the nicknames list changes. """ |
nicknames = [{"nickname": name, "color": color(name)}
for name in sorted(self.nicknames.keys())]
self.namespace.emit("nicknames", nicknames) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_join(self, connection, event):
""" Someone joined the channel - send the nicknames list to the WebSocket. """ |
#from time import sleep; sleep(10) # Simulate a slow connection
nickname = self.get_nickname(event)
nickname_color = color(nickname)
self.nicknames[nickname] = nickname_color
self.namespace.emit("join")
self.namespace.emit("message", nickname, "joins", nickname_color)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_nick(self, connection, event):
""" Someone changed their nickname - send the nicknames list to the WebSocket. """ |
old_nickname = self.get_nickname(event)
old_color = self.nicknames.pop(old_nickname)
new_nickname = event.target()
message = "is now known as %s" % new_nickname
self.namespace.emit("message", old_nickname, message, old_color)
new_color = color(new_nickname)
self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_quit(self, connection, event):
""" Someone left the channel - send the nicknames list to the WebSocket. """ |
nickname = self.get_nickname(event)
nickname_color = self.nicknames[nickname]
del self.nicknames[nickname]
self.namespace.emit("message", nickname, "leaves", nickname_color)
self.emit_nicknames() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_pubmsg(self, connection, event):
""" Messages received in the channel - send them to the WebSocket. """ |
for message in event.arguments():
nickname = self.get_nickname(event)
nickname_color = self.nicknames[nickname]
self.namespace.emit("message", nickname, message, nickname_color) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def perms_for_user(cls, instance, user, db_session=None):
""" returns all permissions that given user has for this resource from groups and directly set ones too... |
db_session = get_db_session(db_session, instance)
query = db_session.query(
cls.models_proxy.GroupResourcePermission.group_id.label("owner_id"),
cls.models_proxy.GroupResourcePermission.perm_name,
sa.literal("group").label("type"),
)
query = query.fil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def direct_perms_for_user(cls, instance, user, db_session=None):
""" returns permissions that given user has for this resource without ones inherited from groups... |
db_session = get_db_session(db_session, instance)
query = db_session.query(
cls.models_proxy.UserResourcePermission.user_id,
cls.models_proxy.UserResourcePermission.perm_name,
)
query = query.filter(cls.models_proxy.UserResourcePermission.user_id == user.id)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def group_perms_for_user(cls, instance, user, db_session=None):
""" returns permissions that given user has for this resource that are inherited from groups :par... |
db_session = get_db_session(db_session, instance)
perms = resource_permissions_for_users(
cls.models_proxy,
ANY_PERMISSION,
resource_ids=[instance.resource_id],
user_ids=[user.id],
db_session=db_session,
)
perms = [p for p in p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def by_resource_id(cls, resource_id, db_session=None):
""" fetch the resouce by id :param resource_id: :param db_session: :return: """ |
db_session = get_db_session(db_session)
query = db_session.query(cls.model).filter(
cls.model.resource_id == int(resource_id)
)
return query.first() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def perm_by_group_and_perm_name( cls, resource_id, group_id, perm_name, db_session=None ):
""" fetch permissions by group and permission name :param resource_id:... |
db_session = get_db_session(db_session)
query = db_session.query(cls.models_proxy.GroupResourcePermission)
query = query.filter(
cls.models_proxy.GroupResourcePermission.group_id == group_id
)
query = query.filter(
cls.models_proxy.GroupResourcePermission... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lock_resource_for_update(cls, resource_id, db_session):
""" Selects resource for update - locking access for other transactions :param resource_id: :param db... |
db_session = get_db_session(db_session)
query = db_session.query(cls.model)
query = query.filter(cls.model.resource_id == resource_id)
query = query.with_for_update()
return query.first() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 :... |
db_session = get_db_session(db_session, instance)
query = db_session.query(
cls.models_proxy.GroupPermission.group_id.label("owner_id"),
cls.models_proxy.GroupPermission.perm_name.label("perm_name"),
sa.literal("group").label("type"),
)
query = query.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def groups_with_resources(cls, instance):
""" Returns a list of groups users belongs to with eager loaded resources owned by those groups :param instance: :retur... |
return instance.groups_dynamic.options(
sa.orm.eagerload(cls.models_proxy.Group.resources)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resources_with_possible_perms( cls, instance, resource_ids=None, resource_types=None, db_session=None ):
""" returns list of permissions and resources for th... |
perms = resource_permissions_for_users(
cls.models_proxy,
ANY_PERMISSION,
resource_ids=resource_ids,
resource_types=resource_types,
user_ids=[instance.id],
db_session=db_session,
)
for resource in instance.resources:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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()
if "d" not in kwargs:
kwargs["d"] = default
params = "&".join(
[
six.moves.urllib.parse.urlencode({key: value})
for key, value in kwargs.item... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.passwordmanager, "hash", instance.passwordmanager.encrypt
)
password = hash_callable(raw_password)
if six.PY2:
instance.user_password = password.decode("utf8")
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_password(cls, instance, raw_password, enable_hash_migration=True):
""" checks string with users password hash using password manager :param instance: :... |
verified, replacement_hash = instance.passwordmanager.verify_and_update(
raw_password, instance.user_password
)
if enable_hash_migration and replacement_hash:
if six.PY2:
instance.user_password = replacement_hash.decode("utf8")
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)
query = query.options(sa.orm.eagerload("groups"))
return query.first() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: :para... |
db_session = get_db_session(db_session)
query = db_session.query(cls.model)
query = query.filter(
sa.func.lower(cls.model.user_name) == (user_name or "").lower()
)
query = query.filter(cls.model.security_code == security_code)
return query.first() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 = db_session.query(cls.model)
query = query.filter(sa.func.lower(cls.model.user_name).in_(user_names))
# q = q.options(sa.orm.eagerload(cls.groups))
return query |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.filter(
sa.func.lower(cls.model.user_name).like((user_name or "").lower())
)
query = query.order_by(cls.model.user_name)
# q = q.options(sa.orm.eagerload('groups'))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) == (email or "").lower()
)
query = query.options(sa.orm.eagerload("groups"))
return query.first() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.filter(
cls.models_proxy.User.id == cls.models_proxy.UserGroup.user_id
)
query = query.filter(
cls.models_proxy.UserGroup.group_id
== cls.models_proxy.Gr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 * 60),
("minute", 60),
("second", 1),
)
delta = datetime.now() - when
total_seconds = delta.days * 60 *... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def version(self, event):
""" Shows version information. """ |
name = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
return "%s [%s]" % (settings.GNOTTY_VERSION_STRING, name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commands(self, event):
""" Lists all available commands. """ |
commands = sorted(self.commands_dict().keys())
return "Available commands: %s" % " ".join(commands) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 comman... |
if command_name is None:
return ("Type !commands for a list of all commands. Type "
"!help [command] to see help for a specific command.")
try:
command = self.commands_dict()[command_name]
except KeyError:
return "%s is not a command" % co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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[nickname])
except KeyError:
return "%s is not in the channel" % nickname
else:
if nickname == self.get_nickname(event):
pre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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):
prefix = "you are"
else:
prefix = "%s is" % nickname
return "%s here right now" % prefix
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def id(self):
""" Unique identifier of user object""" |
return sa.Column(sa.Integer, primary_key=True, autoincrement=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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(),
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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",
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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__)
)
return permission |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 bee... |
if parse:
for feed_url in self.feeds:
feed = parse(feed_url)
for item in feed.entries:
if item["id"] not in self.feed_items:
self.feed_items.add(item["id"])
if message_channel:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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', channel)
for reading in m.readings[nmi][channel][-rows:]:
print('', reading) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:... |
m = read_nem_file(file_name)
if nmi is None:
nmi = list(m.readings.keys())[0] # Use first NMI
channels = list(m.transactions[nmi].keys())
num_records = len(m.readings[nmi][channels[0]])
last_date = m.readings[nmi][channels[0]][-1].t_end
if output_file is None:
output_file = '... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)
return query.first() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
if not GET_params:
GET_params = {}
GET_params.pop("page", None)
query = instance.users_dynamic
if user_ids:
query = query.filter(cls.models_proxy.UserGroup.user_id.in_(user_ids))
return SqlalchemyOrmPage(
query,
page=page,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resources_with_possible_perms( cls, instance, perm_names=None, resource_ids=None, resource_types=None, db_session=None, ):
""" returns list of permissions an... |
db_session = get_db_session(db_session, instance)
query = db_session.query(
cls.models_proxy.GroupResourcePermission.perm_name,
cls.models_proxy.Group,
cls.models_proxy.Resource,
)
query = query.filter(
cls.models_proxy.Resource.resource_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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._free:
conn = self._free.popleft()
if not conn.closed:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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,
echo=self._echo,
loop=self._loop,
**self._conn_kwargs
)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] = function |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_related_kwargs.items():
# delete old kwarg that was related to generic key
del kwargs[key]
try:
suff... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
size = data.shape[0]
df_uv = data.apply(
lambda se: (
(se.dropna().unique().shape[0]/size) > max_unique_values and
se.dtype in ['object', 'category']
)
)
data.drop(df_uv[df_uv].index, axis=1, inplace=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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'] = obj._meta.object_name.lower()
return self._default_view_name... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:
raise AttributeError('Related object does not have any of lookup_fields')
request = self._get_req... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.__class__
except ValueError:
raise serializers.ValidationError(_('URL is invalid: %s.')... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 Exception as e:
# Logging should never break workflow.
l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 %s. Probably it was deleted.' %
serialized_instance)
six.reraise(ObjectDoesNotExist, message)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 = inspect.reserved() or {}
uncompleted = sum(list(active.values()) + list(scheduled.values()) + reserved.values(), [])
return any(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
logger.info(message)
# It is expected by Celery that apply_async return AsyncResult, otherwise celerybeat dies
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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(PenalizedBackgroundTask, self).apply_async(args=args, kwargs=kwargs, **options)
cache.set(key, (counter - 1, penalty), self.CACHE_LIFETIME)
logger.info('Th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.debug('The task %s is penalized and will be executed on %d run.' % (self.name, penalty))
cache.set(key, (penalty, penalty), self.CACHE_LIFE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)
return super(PenalizedBackgroundTask, self).on_success(retval, task_id, args, kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 None else action
logger.debug('About to %s `%s` (PK: %s).', action_name, instance, instance.pk)
result = func(se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.