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 _get_username_hostname():
'''Best attempt to get username and hostname, returns "na" if problem.'''
user = 'na'
host = 'na'
try:
user = getpass.getuser()
except Exception:
pass
try:
host = socket.gethostname()
except Exception:
pass
return user, host
|
<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_details(self, response):
""" Complete with additional information from original LTI POST data, as available. """
|
data = {}
# None of them is mandatory
data['id'] = response.get('user_id', None)
data['username'] = response.get('custom_username', None)
if not data['username']:
data['username'] = response.get('ext_user_username', None)
data['last_name'] = response.get('lis_person_name_family', None)
data['email'] = response.get(
'lis_person_contact_email_primary', None)
data['first_name'] = response.get('lis_person_name_given', None)
data['fullname'] = response.get('lis_person_name_full', None)
logger.debug("User details being used: " + str(data))
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 user_unicode(self):
'''
Monkey patch for getting better user name stringification,
user proxies did not make the job.
Django's custom user model feature would have needed to be introduced
before the first syncdb, which does not work for existing installations.
'''
if self.email:
shortened = self.email.split('@')[0]
return '%s %s (%s@...)' % (self.first_name, self.last_name, shortened)
elif self.first_name or self.last_name:
return '%s %s' % (self.first_name, self.last_name)
elif self.username:
return '%s' % (self.username)
else:
return 'User %u' % (self.pk)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def move_user_data(primary, secondary):
'''
Moves all submissions and other data linked to the secondary user into the primary user.
Nothing is deleted here, we just modify foreign user keys.
'''
# Update all submission authorships of the secondary to the primary
submissions = Submission.objects.filter(authors__id=secondary.pk)
for subm in submissions:
if subm.submitter == secondary:
subm.submitter = primary
subm.authors.remove(secondary)
subm.authors.add(primary)
subm.save()
# Transfer course registrations
try:
for course in secondary.profile.courses.all():
primary.profile.courses.add(course)
primary.profile.save()
except UserProfile.DoesNotExist:
# That's a database consistency problem, but he will go away anyway
pass
|
<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_course_safe(self, id):
'''
Adds a course for the user after conducting a set of sanity checks.
Return the title of the course or an exception.
'''
course = get_object_or_404(Course, pk=int(id), active=True)
if course not in self.courses.all():
self.courses.add(course)
return course.title
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def tutor_courses(self):
'''
Returns the list of courses this user is tutor or owner for.
'''
tutoring = self.user.courses_tutoring.all().filter(active__exact=True)
owning = self.user.courses.all().filter(active__exact=True)
result = (tutoring | owning).distinct()
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 user_courses(self):
'''
Returns the list of courses this user is subscribed for,
or owning, or tutoring.
This leads to the fact that tutors and owners don't need
course membership.
'''
registered = self.courses.filter(active__exact=True).distinct()
return (self.tutor_courses() | registered).distinct()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def open_assignments(self):
'''
Returns the list of open assignments from the
viewpoint of this user.
'''
# Include only assignments with future, or no, hard deadline
qs = Assignment.objects.filter(hard_deadline__gt=timezone.now(
)) | Assignment.objects.filter(hard_deadline__isnull=True)
# Include only assignments that are already published,
# as long as you are not a tutor / course owner
if not self.can_see_future():
qs = qs.filter(publish_at__lt=timezone.now())
# Include only assignments from courses that you are registered for
qs = qs.filter(course__in=self.user_courses())
# Ordering of resulting list
qs = qs.order_by('soft_deadline', '-gradingScheme', 'title')
waiting_for_action = [subm.assignment for subm in self.user.authored.all(
).exclude(state=Submission.WITHDRAWN)]
# Emulate is_null sorting for soft_deadline
qs_without_soft_deadline = qs.filter(soft_deadline__isnull=True)
qs_with_soft_deadline = qs.filter(soft_deadline__isnull=False)
ass_list = [
ass for ass in qs_without_soft_deadline if ass not in waiting_for_action]
ass_list += [
ass for ass in qs_with_soft_deadline if ass not in waiting_for_action]
return ass_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 gone_assignments(self):
'''
Returns the list of past assignments the user did not submit for
before the hard deadline.
'''
# Include only assignments with past hard deadline
qs = Assignment.objects.filter(hard_deadline__lt=timezone.now())
# Include only assignments from courses this user is registered for
qs = qs.filter(course__in=self.user_courses())
# Include only assignments this user has no submission for
return qs.order_by('-hard_deadline')
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_message(self, to, text, subject=None, mtype=None, unsubscribe_url=None):
"""Constructs a MIME message from message and dispatch models."""
|
# TODO Maybe file attachments handling through `files` message_model context var.
if subject is None:
subject = u'%s' % _('No Subject')
if mtype == 'html':
msg = self.mime_multipart()
text_part = self.mime_multipart('alternative')
text_part.attach(self.mime_text(strip_tags(text), _charset='utf-8'))
text_part.attach(self.mime_text(text, 'html', _charset='utf-8'))
msg.attach(text_part)
else:
msg = self.mime_text(text, _charset='utf-8')
msg['From'] = self.from_email
msg['To'] = to
msg['Subject'] = subject
if unsubscribe_url:
msg['List-Unsubscribe'] = '<%s>' % unsubscribe_url
return msg
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def _social_auth_login(self, request, **kwargs):
'''
View function that redirects to social auth login,
in case the user is not logged in.
'''
if request.user.is_authenticated():
if not request.user.is_active or not request.user.is_staff:
raise PermissionDenied()
else:
messages.add_message(request, messages.WARNING, 'Please authenticate first.')
return redirect_to_login(request.get_full_path())
|
<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_queryset(self, request):
''' Restrict the listed courses for the current user.'''
qs = super(CourseAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs
else:
return qs.filter(Q(tutors__pk=request.user.pk) | Q(owner=request.user)).distinct()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def _build_tag_families(tagged_paired_aligns,
ranked_tags,
hamming_threshold,
consensus_threshold,
family_filter=lambda _: None):
'''Partition paired aligns into families.
Each read is considered against each ranked tag until all reads are
partitioned into families.'''
tag_aligns = defaultdict(set)
tag_inexact_match_count = defaultdict(int)
for paired_align in tagged_paired_aligns:
(left_umt, right_umt) = paired_align.umt
for best_tag in ranked_tags:
if paired_align.umt == best_tag:
tag_aligns[best_tag].add(paired_align)
break
elif left_umt == best_tag[0] or right_umt == best_tag[1]:
tag_aligns[best_tag].add(paired_align)
tag_inexact_match_count[best_tag] += 1
break
elif (_hamming_dist(left_umt, best_tag[0]) <= hamming_threshold) \
or (_hamming_dist(right_umt, best_tag[1]) <= hamming_threshold):
tag_aligns[best_tag].add(paired_align)
tag_inexact_match_count[best_tag] += 1
break
tag_families = []
for tag in sorted(tag_aligns):
tag_family = TagFamily(tag,
tag_aligns[tag],
tag_inexact_match_count[tag],
consensus_threshold,
family_filter)
tag_families.append(tag_family)
return tag_families
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def _rank_tags(tagged_paired_aligns):
'''Return the list of tags ranked from most to least popular.'''
tag_count_dict = defaultdict(int)
for paired_align in tagged_paired_aligns:
tag_count_dict[paired_align.umt] += 1
tags_by_count = utils.sort_dict(tag_count_dict)
ranked_tags = [tag_count[0] for tag_count in tags_by_count]
return ranked_tags
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def main(command_line_args=None):
'''Connor entry point. See help for more info'''
log = None
if not command_line_args:
command_line_args = sys.argv
try:
start_time = time.time()
args = parse_command_line_args(command_line_args)
log = utils.Logger(args)
command_validator.preflight(args, log)
log.info('connor begins (v{})', __version__)
log.info('logging to [{}]', args.log_file)
utils.log_environment_info(log, args)
bam_tags = bamtag.build_bam_tags()
base_annotated_writer = writers.build_writer(args.input_bam,
args.annotated_output_bam,
bam_tags,
args)
sort_filter_by_name = args.filter_order == 'name'
annotated_writer = writers.LoggingWriter(base_annotated_writer,
log,
sort_filter_by_name)
consensus_writer = writers.build_writer(args.input_bam,
args.output_bam,
bam_tags,
args)
_dedup_alignments(args, consensus_writer, annotated_writer, log)
annotated_writer.close(log)
consensus_writer.close(log)
warning = ' **See warnings above**' if log.warning_occurred else ''
elapsed_time = int(time.time() - start_time)
log.info("connor complete ({} seconds, {}mb peak memory).{}",
elapsed_time,
utils.peak_memory(),
warning)
except utils.UsageError as usage_error:
message = "connor usage problem: {}".format(str(usage_error))
print(message, file=sys.stderr)
print("See 'connor --help'.", file=sys.stderr)
sys.exit(1)
except Exception: #pylint: disable=broad-except
if log:
show = log.error
else:
show = partial(print, file=sys.stderr)
show("An unexpected error occurred")
show(traceback.format_exc())
exit(1)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule_email(message, to, subject=None, sender=None, priority=None):
"""Schedules an email message for delivery. :param dict, str message: str or dict: use str for simple text email; dict - to compile email from a template (default: `sitemessage/messages/email_html__smtp.html`). :param list|str|unicode to: recipients addresses or Django User model heir instances :param str subject: email subject :param User sender: User model heir instance :param int priority: number describing message priority. If set overrides priority provided with message type. """
|
if SHORTCUT_EMAIL_MESSAGE_TYPE:
message_cls = get_registered_message_type(SHORTCUT_EMAIL_MESSAGE_TYPE)
else:
if isinstance(message, dict):
message_cls = EmailHtmlMessage
else:
message_cls = EmailTextMessage
schedule_messages(
message_cls(subject, message),
recipients(SHORTCUT_EMAIL_MESSENGER_TYPE, to),
sender=sender, priority=priority
)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule_jabber_message(message, to, sender=None, priority=None):
"""Schedules Jabber XMPP message for delivery. :param str message: text to send. :param list|str|unicode to: recipients addresses or Django User model heir instances with `email` attributes. :param User sender: User model heir instance :param int priority: number describing message priority. If set overrides priority provided with message type. """
|
schedule_messages(message, recipients('xmppsleek', to), sender=sender, priority=priority)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule_tweet(message, to='', sender=None, priority=None):
"""Schedules a Tweet for delivery. :param str message: text to send. :param list|str|unicode to: recipients addresses or Django User model heir instances with `telegram` attributes. If supplied tweets will be @-replies. :param User sender: User model heir instance :param int priority: number describing message priority. If set overrides priority provided with message type. """
|
schedule_messages(message, recipients('twitter', to), sender=sender, priority=priority)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule_telegram_message(message, to, sender=None, priority=None):
"""Schedules Telegram message for delivery. :param str message: text to send. :param list|str|unicode to: recipients addresses or Django User model heir instances with `telegram` attributes. :param User sender: User model heir instance :param int priority: number describing message priority. If set overrides priority provided with message type. """
|
schedule_messages(message, recipients('telegram', to), sender=sender, priority=priority)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule_facebook_message(message, sender=None, priority=None):
"""Schedules Facebook wall message for delivery. :param str message: text or URL to publish. :param User sender: User model heir instance :param int priority: number describing message priority. If set overrides priority provided with message type. """
|
schedule_messages(message, recipients('fb', ''), sender=sender, priority=priority)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule_vkontakte_message(message, to, sender=None, priority=None):
"""Schedules VKontakte message for delivery. :param str message: text or URL to publish on wall. :param list|str|unicode to: recipients addresses or Django User model heir instances with `vk` attributes. :param User sender: User model heir instance :param int priority: number describing message priority. If set overrides priority provided with message type. """
|
schedule_messages(message, recipients('vk', to), sender=sender, priority=priority)
|
<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_alias(cls):
"""Returns messenger alias. :return: str :rtype: str """
|
if cls.alias is None:
cls.alias = cls.__name__
return cls.alias
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _structure_recipients_data(cls, recipients):
"""Converts recipients data into a list of Recipient objects. :param list recipients: list of objects :return: list of Recipient :rtype: list """
|
try: # That's all due Django 1.7 apps loading.
from django.contrib.auth import get_user_model
USER_MODEL = get_user_model()
except ImportError:
# Django 1.4 fallback.
from django.contrib.auth.models import User as USER_MODEL
if not is_iterable(recipients):
recipients = (recipients,)
objects = []
for r in recipients:
user = None
if isinstance(r, USER_MODEL):
user = r
address = cls.get_address(r) # todo maybe raise an exception of not a string?
objects.append(Recipient(cls.get_alias(), user, address))
return objects
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mark_error(self, dispatch, error_log, message_cls):
"""Marks a dispatch as having error or consequently as failed if send retry limit for that message type is exhausted. Should be used within send(). :param Dispatch dispatch: a Dispatch :param str error_log: error message :param MessageBase message_cls: MessageBase heir """
|
if message_cls.send_retry_limit is not None and (dispatch.retry_count + 1) >= message_cls.send_retry_limit:
self.mark_failed(dispatch, error_log)
else:
dispatch.error_log = error_log
self._st['error'].append(dispatch)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mark_failed(self, dispatch, error_log):
"""Marks a dispatch as failed. Sitemessage won't try to deliver already failed messages. Should be used within send(). :param Dispatch dispatch: a Dispatch :param str error_log: str - error message """
|
dispatch.error_log = error_log
self._st['failed'].append(dispatch)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_messages(self, messages, ignore_unknown_message_types=False):
"""Performs message processing. :param dict messages: indexed by message id dict with messages data :param bool ignore_unknown_message_types: whether to silence exceptions :raises UnknownMessageTypeError: """
|
with self.before_after_send_handling():
for message_id, message_data in messages.items():
message_model, dispatch_models = message_data
try:
message_cls = get_registered_message_type(message_model.cls)
except UnknownMessageTypeError:
if ignore_unknown_message_types:
continue
raise
message_type_cache = None
for dispatch in dispatch_models:
if not dispatch.message_cache: # Create actual message text for further usage.
try:
if message_type_cache is None and not message_cls.has_dynamic_context:
# If a message class doesn't depend upon a dispatch data for message compilation,
# we'd compile a message just once.
message_type_cache = message_cls.compile(message_model, self, dispatch=dispatch)
dispatch.message_cache = message_type_cache or message_cls.compile(
message_model, self, dispatch=dispatch)
except Exception as e:
self.mark_error(dispatch, e, message_cls)
self.send(message_cls, message_model, dispatch_models)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def setup(self, app):
'''
Make sure that other installed plugins don't affect the same keyword argument.
'''
for other in app.plugins:
if not isinstance(other, MySQLPlugin):
continue
if other.keyword == self.keyword:
raise PluginError("Found another mysql plugin with conflicting settings (non-unique keyword).")
elif other.name == self.name:
self.name += '_%s' % self.keyword
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def assign_role(backend, user, response, *args, **kwargs):
'''
Part of the Python Social Auth Pipeline.
Checks if the created demo user should be pushed into some group.
'''
if backend.name is 'passthrough' and settings.DEMO is True and 'role' in kwargs['request'].session[passthrough.SESSION_VAR]:
role = kwargs['request'].session[passthrough.SESSION_VAR]['role']
if role == 'tutor':
make_tutor(user)
if role == 'admin':
make_admin(user)
if role == 'owner':
make_owner(user)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def fetch(url, fullpath):
'''
Fetch data from an URL and save it under the given target name.
'''
logger.debug("Fetching %s from %s" % (fullpath, url))
try:
tmpfile, headers = urlretrieve(url)
if os.path.exists(fullpath):
os.remove(fullpath)
shutil.move(tmpfile, fullpath)
except Exception as e:
logger.error("Error during fetching: " + str(e))
raise
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def send_post(config, urlpath, post_data):
'''
Send POST data to an OpenSubmit server url path,
according to the configuration.
'''
server = config.get("Server", "url")
logger.debug("Sending executor payload to " + server)
post_data = urlencode(post_data)
post_data = post_data.encode("utf-8", errors="ignore")
url = server + urlpath
try:
urlopen(url, post_data)
except Exception as e:
logger.error('Error while sending data to server: ' + str(e))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def send_hostinfo(config):
'''
Register this host on OpenSubmit test machine.
'''
info = all_host_infos()
logger.debug("Sending host information: " + str(info))
post_data = [("Config", json.dumps(info)),
("Action", "get_config"),
("UUID", config.get("Server", "uuid")),
("Address", ipaddress()),
("Secret", config.get("Server", "secret"))
]
send_post(config, "/machines/", post_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 compatible_api_version(server_version):
'''
Check if this server API version is compatible to us.
'''
try:
semver = server_version.split('.')
if semver[0] != '1':
logger.error(
'Server API version (%s) is too new for us. Please update the executor installation.' % server_version)
return False
else:
return True
except Exception:
logger.error(
'Cannot understand the server API version (%s). Please update the executor installation.' % server_version)
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 fetch_job(config):
'''
Fetch any available work from the OpenSubmit server and
return an according job object.
Returns None if no work is available.
Errors are reported by this function directly.
'''
url = "%s/jobs/?Secret=%s&UUID=%s" % (config.get("Server", "url"),
config.get("Server", "secret"),
config.get("Server", "uuid"))
try:
# Fetch information from server
result = urlopen(url)
headers = result.info()
logger.debug("Raw job data: " + str(result.headers).replace('\n', ', '))
if not compatible_api_version(headers["APIVersion"]):
# No proper reporting possible, so only logging.
logger.error("Incompatible API version. Please update OpenSubmit.")
return None
if headers["Action"] == "get_config":
# The server does not know us,
# so it demands registration before hand.
logger.info("Machine unknown on server, sending registration ...")
send_hostinfo(config)
return None
# Create job object with information we got
from .job import Job
job = Job(config)
job.submitter_name = headers['SubmitterName']
job.author_names = headers['AuthorNames']
job.submitter_studyprogram = headers['SubmitterStudyProgram']
job.course = headers['Course']
job.assignment = headers['Assignment']
job.action = headers["Action"]
job.file_id = headers["SubmissionFileId"]
job.sub_id = headers["SubmissionId"]
job.file_name = headers["SubmissionOriginalFilename"]
job.submitter_student_id = headers["SubmitterStudentId"]
if "Timeout" in headers:
job.timeout = int(headers["Timeout"])
if "PostRunValidation" in headers:
# Ignore server-given host + port and use the configured one instead
# This fixes problems with the arbitrary Django LiveServer port choice
# It would be better to return relative URLs only for this property,
# but this is a Bernhard-incompatible API change
from urllib.parse import urlparse
relative_path = urlparse(headers["PostRunValidation"]).path
job.validator_url = config.get("Server", "url") + relative_path
job.working_dir = create_working_dir(config, job.sub_id)
# Store submission in working directory
submission_fname = job.working_dir + job.file_name
with open(submission_fname, 'wb') as target:
target.write(result.read())
assert(os.path.exists(submission_fname))
# Store validator package in working directory
validator_fname = job.working_dir + 'download.validator'
fetch(job.validator_url, validator_fname)
try:
prepare_working_directory(job, submission_fname, validator_fname)
except JobException as e:
job.send_fail_result(e.info_student, e.info_tutor)
return None
logger.debug("Got job: " + str(job))
return job
except HTTPError as e:
if e.code == 404:
logger.debug("Nothing to do.")
return None
except URLError as e:
logger.error("Error while contacting {0}: {1}".format(url, str(e)))
return None
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def fake_fetch_job(config, src_dir):
'''
Act like fetch_job, but take the validator file and the student
submission files directly from a directory.
Intended for testing purposes when developing test scripts.
Check also cmdline.py.
'''
logger.debug("Creating fake job from " + src_dir)
from .job import Job
job = Job(config, online=False)
job.working_dir = create_working_dir(config, '42')
for fname in glob.glob(src_dir + os.sep + '*'):
logger.debug("Copying {0} to {1} ...".format(fname, job.working_dir))
shutil.copy(fname, job.working_dir)
case_files = glob.glob(job.working_dir + os.sep + '*')
assert(len(case_files) == 2)
if os.path.basename(case_files[0]) in ['validator.py', 'validator.zip']:
validator = case_files[0]
submission = case_files[1]
else:
validator = case_files[1]
submission = case_files[0]
logger.debug('{0} is the validator.'.format(validator))
logger.debug('{0} the submission.'.format(submission))
try:
prepare_working_directory(job,
submission_path=submission,
validator_path=validator)
except JobException as e:
job.send_fail_result(e.info_student, e.info_tutor)
return None
logger.debug("Got fake job: " + str(job))
return job
|
<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_configure(self, mandatory=True):
"""Runs the 'configure' program in the working directory. Args: mandatory (bool):
Throw exception if 'configure' fails or a 'configure' file is missing. """
|
if not has_file(self.working_dir, 'configure'):
if mandatory:
raise FileNotFoundError(
"Could not find a configure script for execution.")
else:
return
try:
prog = RunningProgram(self, 'configure')
prog.expect_exit_status(0)
except Exception:
if mandatory:
raise
|
<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_compiler(self, compiler=GCC, inputs=None, output=None):
"""Runs a compiler in the working directory. Args: compiler (tuple):
The compiler program and its command-line arguments, including placeholders for output and input files. inputs (tuple):
The list of input files for the compiler. output (str):
The name of the output file. """
|
# Let exceptions travel through
prog = RunningProgram(self, *compiler_cmdline(compiler=compiler,
inputs=inputs,
output=output))
prog.expect_exit_status(0)
|
<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_build(self, compiler=GCC, inputs=None, output=None):
"""Combined call of 'configure', 'make' and the compiler. The success of 'configure' and 'make' is optional. The arguments are the same as for run_compiler. """
|
logger.info("Running build steps ...")
self.run_configure(mandatory=False)
self.run_make(mandatory=False)
self.run_compiler(compiler=compiler,
inputs=inputs,
output=output)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spawn_program(self, name, arguments=[], timeout=30, exclusive=False):
"""Spawns a program in the working directory. This method allows the interaction with the running program, based on the returned RunningProgram object. Args: name (str):
The name of the program to be executed. arguments (tuple):
Command-line arguments for the program. timeout (int):
The timeout for execution. exclusive (bool):
Prevent parallel validation runs on the test machines, e.g. when doing performance measurements for submitted code. Returns: RunningProgram: An object representing the running program. """
|
logger.debug("Spawning program for interaction ...")
if exclusive:
kill_longrunning(self.config)
return RunningProgram(self, name, arguments, timeout)
|
<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_program(self, name, arguments=[], timeout=30, exclusive=False):
"""Runs a program in the working directory to completion. Args: name (str):
The name of the program to be executed. arguments (tuple):
Command-line arguments for the program. timeout (int):
The timeout for execution. exclusive (bool):
Prevent parallel validation runs on the test machines, e.g. when doing performance measurements for submitted code. Returns: tuple: A tuple of the exit code, as reported by the operating system, and the output produced during the execution. """
|
logger.debug("Running program ...")
if exclusive:
kill_longrunning(self.config)
prog = RunningProgram(self, name, arguments, timeout)
return prog.expect_end()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grep(self, regex):
"""Scans the student files for text patterns. Args: regex (str):
Regular expression used for scanning inside the files. Returns: tuple: Names of the matching files in the working directory. """
|
matches = []
logger.debug("Searching student files for '{0}'".format(regex))
for fname in self.student_files:
if os.path.isfile(self.working_dir + fname):
for line in open(self.working_dir + fname, 'br'):
if re.search(regex.encode(), line):
logger.debug("{0} contains '{1}'".format(fname, regex))
matches.append(fname)
return matches
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_files(self, filenames):
"""Checks the student submission for specific files. Args: filenames (tuple):
The list of file names to be cjecked for. Returns: bool: Indicator if all files are found in the student archive. """
|
logger.debug("Testing {0} for the following files: {1}".format(
self.working_dir, filenames))
dircontent = os.listdir(self.working_dir)
for fname in filenames:
if fname not in dircontent:
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 live_chat_banner(context):
""" Display any available live chats as advertisements. """
|
context = copy(context)
# Find any upcoming or current live chat. The Chat date must be less than 5
# days away, or currently in progress.
oldchat = LiveChat.chat_finder.get_last_live_chat()
if oldchat:
context['last_live_chat'] = {
'title': oldchat.title,
'chat_ends_at': oldchat.chat_ends_at,
'expert': oldchat.expert,
'url': reverse('livechat:show_archived_livechat')
}
chat = LiveChat.chat_finder.upcoming_live_chat()
if chat is not None:
context['live_chat_advert'] = {
'title': chat.title,
'description': chat.description,
'expert': chat.expert,
'commenting_closed': chat.comments_closed,
'cancelled': chat.is_cancelled,
'archived': chat.is_archived,
'in_progress': chat.is_in_progress(),
'url': reverse(
'livechat:show_livechat',
kwargs={
'slug': chat.slug}),
'archive_url':reverse('livechat:show_archived_livechat')
}
context['live_chat_advert']['datetime'] = {
'time': chat.chat_starts_at.time,
'date': chat.chat_starts_at.date
}
return context
|
<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_longrunning(config):
'''
Terminate everything under the current user account
that has run too long. This is a final safeguard if
the subprocess timeout stuff is not working.
You better have no production servers running also
under the current user account ...
'''
import psutil
ourpid = os.getpid()
username = psutil.Process(ourpid).username
# Check for other processes running under this account
# Take the timeout definition from the config file
timeout = config.getint("Execution", "timeout")
for proc in psutil.process_iter():
if proc.username == username and proc.pid != ourpid:
runtime = time.time() - proc.create_time
logger.debug("This user already runs %u for %u seconds." %
(proc.pid, runtime))
if runtime > timeout:
logger.debug("Killing %u due to exceeded runtime." % proc.pid)
try:
proc.kill()
except Exception:
logger.error("ERROR killing process %d." % proc.pid)
|
<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_exitstatus(self):
"""Get the exit status of the program execution. Returns: int: Exit status as reported by the operating system, or None if it is not available. """
|
logger.debug("Exit status is {0}".format(self._spawn.exitstatus))
return self._spawn.exitstatus
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expect_output(self, pattern, timeout=-1):
"""Wait until the running program performs some given output, or terminates. Args: pattern: The pattern the output should be checked for. timeout (int):
How many seconds should be waited for the output. The pattern argument may be a string, a compiled regular expression, or a list of any of those types. Strings will be compiled into regular expressions. Returns: int: The index into the pattern list. If the pattern was not a list, it returns 0 on a successful match. Raises: TimeoutException: The output did not match within the given time frame. TerminationException: The program terminated before producing the output. NestedException: An internal problem occured while waiting for the output. """
|
logger.debug("Expecting output '{0}' from '{1}'".format(pattern, self.name))
try:
return self._spawn.expect(pattern, timeout)
except pexpect.exceptions.EOF as e:
logger.debug("Raising termination exception.")
raise TerminationException(instance=self, real_exception=e, output=self.get_output())
except pexpect.exceptions.TIMEOUT as e:
logger.debug("Raising timeout exception.")
raise TimeoutException(instance=self, real_exception=e, output=self.get_output())
except Exception as e:
logger.debug("Expecting output failed: " + str(e))
raise NestedException(instance=self, real_exception=e, output=self.get_output())
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sendline(self, text):
"""Sends an input line to the running program, including os.linesep. Args: text (str):
The input text to be send. Raises: TerminationException: The program terminated before / while / after sending the input. NestedException: An internal problem occured while waiting for the output. """
|
logger.debug("Sending input '{0}' to '{1}'".format(text, self.name))
try:
return self._spawn.sendline(text)
except pexpect.exceptions.EOF as e:
logger.debug("Raising termination exception.")
raise TerminationException(instance=self, real_exception=e, output=self.get_output())
except pexpect.exceptions.TIMEOUT as e:
logger.debug("Raising timeout exception.")
raise TimeoutException(instance=self, real_exception=e, output=self.get_output())
except Exception as e:
logger.debug("Sending input failed: " + str(e))
raise NestedException(instance=self, real_exception=e, output=self.get_output())
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expect_end(self):
"""Wait for the running program to finish. Returns: A tuple with the exit code, as reported by the operating system, and the output produced. """
|
logger.debug("Waiting for termination of '{0}'".format(self.name))
try:
# Make sure we fetch the last output bytes.
# Recommendation from the pexpect docs.
self._spawn.expect(pexpect.EOF)
self._spawn.wait()
dircontent = str(os.listdir(self.job.working_dir))
logger.debug("Working directory after execution: " + dircontent)
return self.get_exitstatus(), self.get_output()
except pexpect.exceptions.EOF as e:
logger.debug("Raising termination exception.")
raise TerminationException(instance=self, real_exception=e, output=self.get_output())
except pexpect.exceptions.TIMEOUT as e:
logger.debug("Raising timeout exception.")
raise TimeoutException(instance=self, real_exception=e, output=self.get_output())
except Exception as e:
logger.debug("Waiting for expected program end failed.")
raise NestedException(instance=self, real_exception=e, output=self.get_output())
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expect_exitstatus(self, exit_status):
"""Wait for the running program to finish and expect some exit status. Args: exit_status (int):
The expected exit status. Raises: WrongExitStatusException: The produced exit status is not the expected one. """
|
self.expect_end()
logger.debug("Checking exit status of '{0}', output so far: {1}".format(
self.name, self.get_output()))
if self._spawn.exitstatus is None:
raise WrongExitStatusException(
instance=self, expected=exit_status, output=self.get_output())
if self._spawn.exitstatus is not exit_status:
raise WrongExitStatusException(
instance=self,
expected=exit_status,
got=self._spawn.exitstatus,
output=self.get_output())
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unsubscribe(request, message_id, dispatch_id, hashed, redirect_to=None):
"""Handles unsubscribe request. :param Request request: :param int message_id: :param int dispatch_id: :param str hashed: :param str redirect_to: :return: """
|
return _generic_view(
'handle_unsubscribe_request', sig_unsubscribe_failed,
request, message_id, dispatch_id, hashed, redirect_to=redirect_to
)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mark_read(request, message_id, dispatch_id, hashed, redirect_to=None):
"""Handles mark message as read request. :param Request request: :param int message_id: :param int dispatch_id: :param str hashed: :param str redirect_to: :return: """
|
if redirect_to is None:
redirect_to = get_static_url('img/sitemessage/blank.png')
return _generic_view(
'handle_mark_read_request', sig_mark_read_failed,
request, message_id, dispatch_id, hashed, redirect_to=redirect_to
)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule_messages(messages, recipients=None, sender=None, priority=None):
"""Schedules a message or messages. :param MessageBase|str|list messages: str or MessageBase heir or list - use str to create PlainTextMessage. :param list|None recipients: recipients addresses or Django User model heir instances If `None` Dispatches should be created before send using `prepare_dispatches()`. :param User|None sender: User model heir instance :param int priority: number describing message priority. If set overrides priority provided with message type. :return: list of tuples - (message_model, dispatches_models) :rtype: list """
|
if not is_iterable(messages):
messages = (messages,)
results = []
for message in messages:
if isinstance(message, six.string_types):
message = PlainTextMessage(message)
resulting_priority = message.priority
if priority is not None:
resulting_priority = priority
results.append(message.schedule(sender=sender, recipients=recipients, priority=resulting_priority))
return results
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_scheduled_messages(priority=None, ignore_unknown_messengers=False, ignore_unknown_message_types=False):
"""Sends scheduled messages. :param int, None priority: number to limit sending message by this priority. :param bool ignore_unknown_messengers: to silence UnknownMessengerError :param bool ignore_unknown_message_types: to silence UnknownMessageTypeError :raises UnknownMessengerError: :raises UnknownMessageTypeError: """
|
dispatches_by_messengers = Dispatch.group_by_messengers(Dispatch.get_unsent(priority=priority))
for messenger_id, messages in dispatches_by_messengers.items():
try:
messenger_obj = get_registered_messenger_object(messenger_id)
messenger_obj._process_messages(messages, ignore_unknown_message_types=ignore_unknown_message_types)
except UnknownMessengerError:
if ignore_unknown_messengers:
continue
raise
|
<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_undelivered(to=None):
"""Sends a notification email if any undelivered dispatches. Returns undelivered (failed) dispatches count. :param str|unicode to: Recipient address. If not set Django ADMINS setting is used. :rtype: int """
|
failed_count = Dispatch.objects.filter(dispatch_status=Dispatch.DISPATCH_STATUS_FAILED).count()
if failed_count:
from sitemessage.shortcuts import schedule_email
from sitemessage.messages.email import EmailTextMessage
if to is None:
admins = settings.ADMINS
if admins:
to = list(dict(admins).values())
if to:
priority = 999
register_message_types(EmailTextMessage)
schedule_email(
'You have %s undelivered dispatch(es) at %s' % (failed_count, get_site_url()),
subject='[SITEMESSAGE] Undelivered dispatches',
to=to, priority=priority)
send_scheduled_messages(priority=priority)
return failed_count
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_dispatches():
"""Automatically creates dispatches for messages without them. :return: list of Dispatch :rtype: list """
|
dispatches = []
target_messages = Message.get_without_dispatches()
cache = {}
for message_model in target_messages:
if message_model.cls not in cache:
message_cls = get_registered_message_type(message_model.cls)
subscribers = message_cls.get_subscribers()
cache[message_model.cls] = (message_cls, subscribers)
else:
message_cls, subscribers = cache[message_model.cls]
dispatches.extend(message_cls.prepare_dispatches(message_model))
return dispatches
|
<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_preferences_for_ui(user, message_filter=None, messenger_filter=None, new_messengers_titles=None):
"""Returns a two element tuple with user subscription preferences to render in UI. Message types with the same titles are merged into one row. First element: A list of messengers titles. Second element: User preferences dictionary indexed by message type titles. Preferences (dictionary values) are lists of tuples: (preference_alias, is_supported_by_messenger_flag, user_subscribed_flag) Example: :param User user: :param callable|None message_filter: A callable accepting a message object to filter out message types :param callable|None messenger_filter: A callable accepting a messenger object to filter out messengers :rtype: tuple """
|
if new_messengers_titles is None:
new_messengers_titles = {}
msgr_to_msg = defaultdict(set)
msg_titles = OrderedDict()
msgr_titles = OrderedDict()
for msgr in get_registered_messenger_objects().values():
if not (messenger_filter is None or messenger_filter(msgr)) or not msgr.allow_user_subscription:
continue
msgr_alias = msgr.alias
msgr_title = new_messengers_titles.get(msgr.alias) or msgr.title
for msg in get_registered_message_types().values():
if not (message_filter is None or message_filter(msg)) or not msg.allow_user_subscription:
continue
msgr_supported = msg.supported_messengers
is_supported = (not msgr_supported or msgr.alias in msgr_supported)
if not is_supported:
continue
msg_alias = msg.alias
msg_titles.setdefault('%s' % msg.title, []).append(msg_alias)
msgr_to_msg[msgr_alias].update((msg_alias,))
msgr_titles[msgr_title] = msgr_alias
def sort_titles(titles):
return OrderedDict(sorted([(k, v) for k, v in titles.items()], key=itemgetter(0)))
msgr_titles = sort_titles(msgr_titles)
user_prefs = OrderedDict()
user_subscriptions = ['%s%s%s' % (pref.message_cls, _ALIAS_SEP, pref.messenger_cls)
for pref in Subscription.get_for_user(user)]
for msg_title, msg_aliases in sort_titles(msg_titles).items():
for __, msgr_alias in msgr_titles.items():
msg_candidates = msgr_to_msg[msgr_alias].intersection(msg_aliases)
alias = ''
msg_supported = False
subscribed = False
if msg_candidates:
alias = '%s%s%s' % (msg_candidates.pop(), _ALIAS_SEP, msgr_alias)
msg_supported = True
subscribed = alias in user_subscriptions
user_prefs.setdefault(msg_title, []).append((alias, msg_supported, subscribed))
return msgr_titles.keys(), user_prefs
|
<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_user_preferences_from_request(request):
"""Sets user subscription preferences using data from a request. Expects data sent by form built with `sitemessage_prefs_table` template tag. :param request: :rtype: bool :return: Flag, whether prefs were found in the request. """
|
prefs = []
for pref in request.POST.getlist(_PREF_POST_KEY):
message_alias, messenger_alias = pref.split(_ALIAS_SEP)
try:
get_registered_message_type(message_alias)
get_registered_messenger_object(messenger_alias)
except (UnknownMessengerError, UnknownMessageTypeError):
pass
else:
prefs.append((message_alias, messenger_alias))
Subscription.replace_for_user(request.user, prefs)
return bool(prefs)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def formfield_for_dbfield(self, db_field, **kwargs):
''' Offer only gradings that are not used by other schemes, which means they are used by this scheme or not at all.'''
if db_field.name == "gradings":
request=kwargs['request']
try:
#TODO: MockRequst object from unit test does not contain path information, so an exception occurs during test.
# Find a test-suite compatible solution here.
obj=resolve(request.path).args[0]
filterexpr=Q(schemes=obj) | Q(schemes=None)
kwargs['queryset'] = Grading.objects.filter(filterexpr).distinct()
except:
pass
return super(GradingSchemeAdmin, self).formfield_for_dbfield(db_field, **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 build_bam_tags():
'''builds the list of BAM tags to be added to output BAMs'''
#pylint: disable=unused-argument
def _combine_filters(fam, paired_align, align):
filters = [x.filter_value for x in [fam, align] if x and x.filter_value]
if filters:
return ";".join(filters).replace('; ', ';')
return None
boolean_tag_value = {True:1}
tags = [
BamTag("X0", "Z",
("filter (why the alignment was excluded)"),
_combine_filters),
BamTag("X1", "Z",
("leftmost~rightmost matched pair positions"),
lambda fam, pair, align: pair.positions('{left}~{right}')),
BamTag("X2", "Z",
("L~R CIGARs"),
lambda fam, pair, align: pair.cigars('{left}~{right}')),
BamTag("X3", "i",
"unique identifier for this alignment family",
lambda fam, pair, align: fam.umi_sequence),
BamTag("X4", "Z",
("L~R UMT barcodes for this alignment family; because "
"of fuzzy matching the family UMT may be distinct "
"from the UMT of the original alignment"),
lambda fam, pair, align: fam.umt('{left}~{right}')),
BamTag("X5", "i",
"family size (number of align pairs in this family)",
lambda fam, pair, align: fam.included_pair_count),
BamTag("X6", "i",
("presence of this tag signals that this alignment "
"would be the template for the consensus alignment"),
lambda fam, pair, align: boolean_tag_value.get(fam.is_consensus_template(align), None))]
return tags
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def current_livechat(request):
""" Checks if a live chat is currently on the go, and add it to the request context. This is to allow the AskMAMA URL in the top-navigation to be redirected to the live chat object view consistently, and to make it available to the views and tags that depends on it. """
|
result = {}
livechat = LiveChat.chat_finder.get_current_live_chat()
if livechat:
result['live_chat'] = {}
result['live_chat']['current_live_chat'] = livechat
can_comment, reason_code = livechat.can_comment(request)
result['live_chat']['can_render_comment_form'] = can_comment
result['live_chat']['can_comment_code'] = reason_code
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 upload_path(instance, filename):
'''
Sanitize the user-provided file name, add timestamp for uniqness.
'''
filename = filename.replace(" ", "_")
filename = unicodedata.normalize('NFKD', filename).lower()
return os.path.join(str(timezone.now().date().isoformat()), filename)
|
<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_archive(self):
'''
Determines if the attachment is an archive.
'''
try:
if zipfile.is_zipfile(self.attachment.path) or tarfile.is_tarfile(self.attachment.path):
return True
except Exception:
pass
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 get_user_details(self, response):
""" Complete with additional information from session, as available. """
|
result = {
'id': response['id'],
'username': response.get('username', None),
'email': response.get('email', None),
'first_name': response.get('first_name', None),
'last_name': response.get('last_name', None)
}
if result['first_name'] and result['last_name']:
result['fullname'] = result['first_name'] + \
' ' + result['last_name']
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 paired_reader_from_bamfile(args,
log,
usage_logger,
annotated_writer):
'''Given a BAM file, return a generator that yields filtered, paired reads'''
total_aligns = pysamwrapper.total_align_count(args.input_bam)
bamfile_generator = _bamfile_generator(args.input_bam)
return _paired_reader(args.umt_length,
bamfile_generator,
total_aligns,
log,
usage_logger,
annotated_writer)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def opencl():
'''
Determine some system information about the installed OpenCL device.
'''
result = []
try:
import pyopencl as ocl
for plt in ocl.get_platforms():
result.append("Platform: " + platform.name)
for device in plt.get_devices():
result.append(" Device:" + device.name.strip())
infoset = [key for key in dir(device) if not key.startswith(
"__") and key not in ["extensions", "name"]]
for attr in infoset:
try:
result.append(" %s: %s" % (
attr.strip(), getattr(device, attr).strip()))
except Exception:
pass
return "\n".join(result)
except Exception:
return ""
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def all_host_infos():
'''
Summarize all host information.
'''
output = []
output.append(["Operating system", os()])
output.append(["CPUID information", cpu()])
output.append(["CC information", compiler()])
output.append(["JDK information", from_cmd("java -version")])
output.append(["MPI information", from_cmd("mpirun -version")])
output.append(["Scala information", from_cmd("scala -version")])
output.append(["OpenCL headers", from_cmd(
"find /usr/include|grep opencl.h")])
output.append(["OpenCL libraries", from_cmd(
"find /usr/lib/ -iname '*opencl*'")])
output.append(["NVidia SMI", from_cmd("nvidia-smi -q")])
output.append(["OpenCL Details", opencl()])
return output
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def _completed_families(self, reference_name, rightmost_boundary):
'''returns one or more families whose end < rightmost boundary'''
in_progress = self._right_coords_in_progress[reference_name]
while len(in_progress):
right_coord = in_progress[0]
if right_coord < rightmost_boundary:
in_progress.pop(0)
left_families = self._coordinate_family.pop((reference_name, right_coord), {})
for family in sorted(left_families.values(),
key=lambda x:x[0].left.reference_start):
family.sort(key=lambda x: x.query_name)
self.pending_pair_count -= len(family)
yield family
else:
break
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def inform_student(submission, request, state):
'''
Create an email message for the student,
based on the given submission state.
Sending eMails on validation completion does
not work, since this may have been triggered
by the admin.
'''
details_url = request.build_absolute_uri(reverse('details', args=(submission.pk,)))
if state == submission.TEST_VALIDITY_FAILED:
subject = STUDENT_FAILED_SUB
message = STUDENT_FAILED_MSG
message = message % (submission.assignment,
submission.assignment.course,
details_url)
elif state == submission.CLOSED:
if submission.assignment.is_graded():
subject = STUDENT_GRADED_SUB
message = STUDENT_GRADED_MSG
else:
subject = STUDENT_PASSED_SUB
message = STUDENT_PASSED_MSG
message = message % (submission.assignment,
submission.assignment.course,
details_url)
else:
return
subject = "[%s] %s" % (submission.assignment.course, subject)
from_email = submission.assignment.course.owner.email
recipients = submission.authors.values_list(
'email', flat=True).distinct().order_by('email')
# send student email with BCC to course owner.
# TODO: This might be configurable later
# email = EmailMessage(subject, message, from_email, recipients,
# [self.assignment.course.owner.email])
email = EmailMessage(subject, message, from_email, recipients)
email.send(fail_silently=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 graded_submissions(self):
'''
Queryset for the graded submissions, which are worth closing.
'''
qs = self._valid_submissions().filter(state__in=[Submission.GRADED])
return qs
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def authors(self):
'''
Queryset for all distinct authors this course had so far. Important for statistics.
Note that this may be different from the list of people being registered for the course,
f.e. when they submit something and the leave the course.
'''
qs = self._valid_submissions().values_list('authors',flat=True).distinct()
return qs
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post_user_login(sender, request, user, **kwargs):
""" Create a profile for the user, when missing. Make sure that all neccessary user groups exist and have the right permissions. We need that automatism for people not calling the configure tool, admin rights for admins after the first login, and similar cases. """
|
logger.debug("Running post-processing for user login.")
# Users created by social login or admins have no profile.
# We fix that during their first login.
try:
with transaction.atomic():
profile, created = UserProfile.objects.get_or_create(user=user)
if created:
logger.info("Created missing profile for user " + str(user.pk))
except Exception as e:
logger.error("Error while creating user profile: " + str(e))
check_permission_system()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def submissionfile_post_save(sender, instance, signal, created, **kwargs):
'''
Update MD5 field for newly uploaded files.
'''
if created:
logger.debug("Running post-processing for new submission file.")
instance.md5 = instance.attachment_md5()
instance.save()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def submission_post_save(sender, instance, **kwargs):
''' Several sanity checks after we got a valid submission object.'''
logger.debug("Running post-processing for submission")
# Make the submitter an author
if instance.submitter not in instance.authors.all():
instance.authors.add(instance.submitter)
instance.save()
# Mark all existing submissions for this assignment by these authors as invalid.
# This fixes a race condition with parallel new submissions in multiple browser windows by the same user.
# Solving this as pre_save security exception does not work, since we have no instance with valid foreign keys to check there.
# Considering that this runs also on tutor correction backend activities, it also serves as kind-of cleanup functionality
# for multiplse submissions by the same students for the same assignment - however they got in here.
if instance.state == instance.get_initial_state():
for author in instance.authors.all():
same_author_subm = User.objects.get(pk=author.pk).authored.all().exclude(
pk=instance.pk).filter(assignment=instance.assignment)
for subm in same_author_subm:
subm.state = Submission.WITHDRAWN
subm.save()
|
<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_subscribers(cls, active_only=True):
"""Returns a list of Recipient objects subscribed for this message type. :param bool active_only: Flag whether :return: """
|
subscribers_raw = Subscription.get_for_message_cls(cls.alias)
subscribers = []
for subscriber in subscribers_raw:
messenger_cls = subscriber.messenger_cls
address = subscriber.address
recipient = subscriber.recipient
# Do not send messages to inactive users.
if active_only and recipient:
if not getattr(recipient, 'is_active', False):
continue
if address is None:
try:
address = get_registered_messenger_object(messenger_cls).get_address(recipient)
except UnknownMessengerError:
pass
if address and isinstance(address, string_types):
subscribers.append(Recipient(messenger_cls, recipient, address))
return subscribers
|
<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(cls, name, message_model, dispatch_model):
"""Returns a common pattern sitemessage URL. :param str name: URL name :param Message message_model: :param Dispatch|None dispatch_model: :return: """
|
global APP_URLS_ATTACHED
url = ''
if dispatch_model is None:
return url
if APP_URLS_ATTACHED != False: # sic!
hashed = cls.get_dispatch_hash(dispatch_model.id, message_model.id)
try:
url = reverse(name, args=[message_model.id, dispatch_model.id, hashed])
url = '%s%s' % (get_site_url(), url)
except NoReverseMatch:
if APP_URLS_ATTACHED is None:
APP_URLS_ATTACHED = False
return url
|
<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_unsubscribe_request(cls, request, message, dispatch, hash_is_valid, redirect_to):
"""Handles user subscription cancelling request. :param Request request: Request instance :param Message message: Message model instance :param Dispatch dispatch: Dispatch model instance :param bool hash_is_valid: Flag indicating that user supplied request signature is correct :param str redirect_to: Redirection URL :rtype: list """
|
if hash_is_valid:
Subscription.cancel(
dispatch.recipient_id or dispatch.address, cls.alias, dispatch.messenger
)
signal = sig_unsubscribe_success
else:
signal = sig_unsubscribe_failed
signal.send(cls, request=request, message=message, dispatch=dispatch)
return redirect(redirect_to)
|
<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_mark_read_request(cls, request, message, dispatch, hash_is_valid, redirect_to):
"""Handles a request to mark a message as read. :param Request request: Request instance :param Message message: Message model instance :param Dispatch dispatch: Dispatch model instance :param bool hash_is_valid: Flag indicating that user supplied request signature is correct :param str redirect_to: Redirection URL :rtype: list """
|
if hash_is_valid:
dispatch.mark_read()
dispatch.save()
signal = sig_mark_read_success
else:
signal = sig_mark_read_failed
signal.send(cls, request=request, message=message, dispatch=dispatch)
return redirect(redirect_to)
|
<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_template(cls, message, messenger):
"""Get a template path to compile a message. 1. `tpl` field of message context; 2. `template` field of message class; 3. deduced from message, messenger data and `template_ext` message type field (e.g. `sitemessage/messages/plain__smtp.txt` for `plain` message type). :param Message message: Message model :param MessengerBase messenger: a MessengerBase heir :return: str :rtype: str """
|
template = message.context.get('tpl', None)
if template: # Template name is taken from message context.
return template
if cls.template is None:
cls.template = 'sitemessage/messages/%s__%s.%s' % (
cls.get_alias(), messenger.get_alias(), cls.template_ext
)
return cls.template
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compile(cls, message, messenger, dispatch=None):
"""Compiles and returns a message text. Considers `use_tpl` field from message context to decide whether template compilation is used. Otherwise a SIMPLE_TEXT_ID field from message context is used as message contents. :param Message message: model instance :param MessengerBase messenger: MessengerBase heir instance :param Dispatch dispatch: model instance to consider context from :return: str :rtype: str """
|
if message.context.get('use_tpl', False):
context = message.context
context.update({
'SITE_URL': get_site_url(),
'directive_unsubscribe': cls.get_unsubscribe_directive(message, dispatch),
'directive_mark_read': cls.get_mark_read_directive(message, dispatch),
'message_model': message,
'dispatch_model': dispatch
})
context = cls.get_template_context(context)
return render_to_string(cls.get_template(message, messenger), context)
return message.context[cls.SIMPLE_TEXT_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 update_context(cls, base_context, str_or_dict, template_path=None):
"""Helper method to structure initial message context data. NOTE: updates `base_context` inplace. :param dict base_context: context dict to update :param dict, str str_or_dict: text representing a message, or a dict to be placed into message context. :param str template_path: template path to be used for message rendering """
|
if isinstance(str_or_dict, dict):
base_context.update(str_or_dict)
base_context['use_tpl'] = True
else:
base_context[cls.SIMPLE_TEXT_ID] = str_or_dict
if cls.SIMPLE_TEXT_ID in str_or_dict:
base_context['use_tpl'] = False
base_context['tpl'] = template_path
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_dispatches(cls, message, recipients=None):
"""Creates Dispatch models for a given message and return them. :param Message message: Message model instance :param list|None recipients: A list or Recipient objects :return: list of created Dispatch models :rtype: list """
|
return Dispatch.create(message, recipients or cls.get_subscribers())
|
<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_page_access_token(self, app_id, app_secret, user_token):
"""Returns a dictionary of never expired page token indexed by page names. :param str app_id: Application ID :param str app_secret: Application secret :param str user_token: User short-lived token :rtype: dict """
|
url_extend = (
self._url_base + '/oauth/access_token?grant_type=fb_exchange_token&'
'client_id=%(app_id)s&client_secret=%(app_secret)s&fb_exchange_token=%(user_token)s')
response = self.lib.get(url_extend % {'app_id': app_id, 'app_secret': app_secret, 'user_token': user_token})
user_token_long_lived = response.text.split('=')[-1]
response = self.lib.get(self._url_versioned + '/me/accounts?access_token=%s' % user_token_long_lived)
json = response.json()
tokens = {item['name']: item['access_token'] for item in json['data'] if item.get('access_token')}
return tokens
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def create_working_dir(config, prefix):
'''
Create a fresh temporary directory, based on the fiven prefix.
Returns the new path.
'''
# Fetch base directory from executor configuration
basepath = config.get("Execution", "directory")
if not prefix:
prefix = 'opensubmit'
finalpath = tempfile.mkdtemp(prefix=prefix + '_', dir=basepath)
if not finalpath.endswith(os.sep):
finalpath += os.sep
logger.debug("Created fresh working directory at {0}.".format(finalpath))
return finalpath
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def prepare_working_directory(job, submission_path, validator_path):
'''
Based on two downloaded files in the working directory,
the student submission and the validation package,
the working directory is prepared.
We unpack student submission first, so that teacher files overwrite
them in case.
When the student submission is a single directory, we change the
working directory and go directly into it, before dealing with the
validator stuff.
If unrecoverable errors happen, such as an empty student archive,
a JobException is raised.
'''
# Safeguard for fail-fast in disk full scenarios on the executor
dusage = shutil.disk_usage(job.working_dir)
if dusage.free < 1024 * 1024 * 50: # 50 MB
info_student = "Internal error with the validator. Please contact your course responsible."
info_tutor = "Error: Execution cancelled, less then 50MB of disk space free on the executor."
logger.error(info_tutor)
raise JobException(info_student=info_student, info_tutor=info_tutor)
submission_fname = os.path.basename(submission_path)
validator_fname = os.path.basename(validator_path)
# Un-archive student submission
single_dir, did_unpack = unpack_if_needed(job.working_dir, submission_path)
job.student_files = os.listdir(job.working_dir)
if did_unpack:
job.student_files.remove(submission_fname)
# Fail automatically on empty student submissions
if len(job.student_files) is 0:
info_student = "Your compressed upload is empty - no files in there."
info_tutor = "Submission archive file has no content."
logger.error(info_tutor)
raise JobException(info_student=info_student, info_tutor=info_tutor)
# Handle student archives containing a single directory with all data
if single_dir:
logger.warning(
"The submission archive contains only one directory. Changing working directory.")
# Set new working directory
job.working_dir = job.working_dir + single_dir + os.sep
# Move validator package there
shutil.move(validator_path, job.working_dir)
validator_path = job.working_dir + validator_fname
# Re-scan for list of student files
job.student_files = os.listdir(job.working_dir)
# The working directory now only contains the student data and the downloaded
# validator package.
# Update the file list accordingly.
job.student_files.remove(validator_fname)
logger.debug("Student files: {0}".format(job.student_files))
# Unpack validator package
single_dir, did_unpack = unpack_if_needed(job.working_dir, validator_path)
if single_dir:
info_student = "Internal error with the validator. Please contact your course responsible."
info_tutor = "Error: Directories are not allowed in the validator archive."
logger.error(info_tutor)
raise JobException(info_student=info_student, info_tutor=info_tutor)
if not os.path.exists(job.validator_script_name):
if did_unpack:
# The download was an archive, but the validator was not inside.
# This is a failure of the tutor.
info_student = "Internal error with the validator. Please contact your course responsible."
info_tutor = "Error: Missing validator.py in the validator archive."
logger.error(info_tutor)
raise JobException(info_student=info_student,
info_tutor=info_tutor)
else:
# The download is already the script, but has the wrong name
logger.warning("Renaming {0} to {1}.".format(
validator_path, job.validator_script_name))
shutil.move(validator_path, job.validator_script_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 django_admin(args):
'''
Run something like it would be done through Django's manage.py.
'''
from django.core.management import execute_from_command_line
from django.core.exceptions import ImproperlyConfigured
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "opensubmit.settings")
try:
execute_from_command_line([sys.argv[0]] + args)
except ImproperlyConfigured as e:
print(str(e))
exit(-1)
|
<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_path(file_path):
'''
Checks if the directories for this path exist, and creates them in case.
'''
directory = os.path.dirname(file_path)
if directory != '':
if not os.path.exists(directory):
os.makedirs(directory, 0o775)
|
<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_file(filepath):
'''
- Checks if the parent directories for this path exist.
- Checks that the file exists.
- Donates the file to the web server user.
TODO: This is Debian / Ubuntu specific.
'''
check_path(filepath)
if not os.path.exists(filepath):
print("WARNING: File does not exist. Creating it: %s" % filepath)
open(filepath, 'a').close()
try:
print("Setting access rights for %s for www-data user" % (filepath))
uid = pwd.getpwnam("www-data").pw_uid
gid = grp.getgrnam("www-data").gr_gid
os.chown(filepath, uid, gid)
os.chmod(filepath, 0o660) # rw-rw---
except Exception:
print("WARNING: Could not adjust file system permissions for %s. Make sure your web server can write into it." % filepath)
|
<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_web_config_consistency(config):
'''
Check the web application config file for consistency.
'''
login_conf_deps = {
'LOGIN_TWITTER_OAUTH_KEY': ['LOGIN_TWITTER_OAUTH_SECRET'],
'LOGIN_GOOGLE_OAUTH_KEY': ['LOGIN_GOOGLE_OAUTH_SECRET'],
'LOGIN_GITHUB_OAUTH_KEY': ['LOGIN_GITHUB_OAUTH_SECRET'],
'LOGIN_GITLAB_OAUTH_KEY': ['LOGIN_GITLAB_OAUTH_SECRET'],
'LOGIN_TWITTER_OAUTH_SECRET': ['LOGIN_TWITTER_OAUTH_KEY'],
'LOGIN_GOOGLE_OAUTH_SECRET': ['LOGIN_GOOGLE_OAUTH_KEY'],
'LOGIN_GITHUB_OAUTH_SECRET': ['LOGIN_GITHUB_OAUTH_KEY'],
'LOGIN_GITLAB_OAUTH_SECRET': ['LOGIN_GITLAB_OAUTH_KEY'],
'LOGIN_OIDC_ENDPOINT': ['LOGIN_OIDC_CLIENT_ID', 'LOGIN_OIDC_CLIENT_SECRET', 'LOGIN_OIDC_DESCRIPTION'],
'LOGIN_OIDC_CLIENT_ID': ['LOGIN_OIDC_ENDPOINT', 'LOGIN_OIDC_CLIENT_SECRET', 'LOGIN_OIDC_DESCRIPTION'],
'LOGIN_OIDC_CLIENT_SECRET': ['LOGIN_OIDC_ENDPOINT', 'LOGIN_OIDC_CLIENT_ID', 'LOGIN_OIDC_DESCRIPTION'],
}
print("Checking configuration of the OpenSubmit web application...")
# Let Django's manage.py load the settings file, to see if this works in general
django_admin(["check"])
# Check configuration dependencies
for k, v in list(login_conf_deps.items()):
if config.get('login', k):
for needed in v:
if len(config.get('login', needed)) < 1:
print(
"ERROR: You have enabled %s in settings.ini, but %s is not set." % (k, needed))
return False
# Check media path
check_path(config.get('server', 'MEDIA_ROOT'))
# Prepare empty log file, in case the web server has no creation rights
log_file = config.get('server', 'LOG_FILE')
print("Preparing log file at " + log_file)
check_file(log_file)
# If SQLite database, adjust file system permissions for the web server
if config.get('database', 'DATABASE_ENGINE') == 'sqlite3':
name = config.get('database', 'DATABASE_NAME')
if not os.path.isabs(name):
print("ERROR: Your SQLite database name must be an absolute path. The web server must have directory access permissions for this path.")
return False
check_file(config.get('database', 'DATABASE_NAME'))
# everything ok
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 check_web_config(config_fname):
'''
Try to load the Django settings.
If this does not work, than settings file does not exist.
Returns:
Loaded configuration, or None.
'''
print("Looking for config file at {0} ...".format(config_fname))
config = RawConfigParser()
try:
config.readfp(open(config_fname))
return config
except IOError:
print("ERROR: Seems like the config file does not exist. Please call 'opensubmit-web configcreate' first, or specify a location with the '-c' option.")
return None
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize_url(url: str) -> str: """ Remove leading and trailing slashes from a URL :param url: URL :return: URL with no leading and trailing slashes :private: """
|
if url.startswith('/'):
url = url[1:]
if url.endswith('/'):
url = url[:-1]
return url
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unwrap(variable_parts: VariablePartsType):
""" Yield URL parts. The given parts are usually in reverse order. """
|
curr_parts = variable_parts
var_any = []
while curr_parts:
curr_parts, (var_type, part) = curr_parts
if var_type == Routes._VAR_ANY_NODE:
var_any.append(part)
continue
if var_type == Routes._VAR_ANY_BREAK:
if var_any:
yield tuple(reversed(var_any))
var_any.clear()
var_any.append(part)
continue
if var_any:
yield tuple(reversed(var_any))
var_any.clear()
yield part
continue
yield part
if var_any:
yield tuple(reversed(var_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 make_params( key_parts: Sequence[str], variable_parts: VariablePartsType) -> Dict[str, Union[str, Tuple[str]]]: """ Map keys to variables. This map\ URL-pattern variables to\ a URL related parts :param key_parts: A list of URL parts :param variable_parts: A linked-list\ (ala nested tuples) of URL parts :return: The param dict with the values\ assigned to the keys :private: """
|
# The unwrapped variable parts are in reverse order.
# Instead of reversing those we reverse the key parts
# and avoid the O(n) space required for reversing the vars
return dict(zip(reversed(key_parts), _unwrap(variable_parts)))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _deconstruct_url(self, url: str) -> List[str]: """ Split a regular URL into parts :param url: A normalized URL :return: Parts of the URL :raises kua.routes.RouteError: \ If the depth of the URL exceeds\ the max depth of the deepest\ registered pattern :private: """
|
parts = url.split('/', self._max_depth + 1)
if depth_of(parts) > self._max_depth:
raise RouteError('No match')
return parts
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _match(self, parts: Sequence[str]) -> RouteResolved: """ Match URL parts to a registered pattern. This function is basically where all\ the CPU-heavy work is done. :param parts: URL parts :return: Matched route :raises kua.routes.RouteError: If there is no match :private: """
|
route_match = None # type: RouteResolved
route_variable_parts = tuple() # type: VariablePartsType
# (route_partial, variable_parts, depth)
to_visit = [(self._routes, tuple(), 0)] # type: List[Tuple[dict, tuple, int]]
# Walk through the graph,
# keep track of all possible
# matching branches and do
# backtracking if needed
while to_visit:
curr, curr_variable_parts, depth = to_visit.pop()
try:
part = parts[depth]
except IndexError:
if self._ROUTE_NODE in curr:
route_match = curr[self._ROUTE_NODE]
route_variable_parts = curr_variable_parts
break
else:
continue
if self._VAR_ANY_NODE in curr:
to_visit.append((
{self._VAR_ANY_NODE: curr[self._VAR_ANY_NODE]},
(curr_variable_parts,
(self._VAR_ANY_NODE, part)),
depth + 1))
to_visit.append((
curr[self._VAR_ANY_NODE],
(curr_variable_parts,
(self._VAR_ANY_BREAK, part)),
depth + 1))
if self._VAR_NODE in curr:
to_visit.append((
curr[self._VAR_NODE],
(curr_variable_parts,
(self._VAR_NODE, part)),
depth + 1))
if part in curr:
to_visit.append((
curr[part],
curr_variable_parts,
depth + 1))
if not route_match:
raise RouteError('No match')
return RouteResolved(
params=make_params(
key_parts=route_match.key_parts,
variable_parts=route_variable_parts),
anything=route_match.anything)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match(self, url: str) -> RouteResolved: """ Match a URL to a registered pattern. :param url: URL :return: Matched route :raises kua.RouteError: If there is no match """
|
url = normalize_url(url)
parts = self._deconstruct_url(url)
return self._match(parts)
|
<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(self, url: str, anything: Any) -> None: """ Register a URL pattern into\ the routes for later matching. It's possible to attach any kind of\ object to the pattern for later\ retrieving. A dict with methods and callbacks,\ for example. Anything really. Registration order does not matter.\ Adding a URL first or last makes no difference. :param url: URL :param anything: Literally anything. """
|
url = normalize_url(url)
parts = url.split('/')
curr_partial_routes = self._routes
curr_key_parts = []
for part in parts:
if part.startswith(':*'):
curr_key_parts.append(part[2:])
part = self._VAR_ANY_NODE
self._max_depth = self._max_depth_custom
elif part.startswith(':'):
curr_key_parts.append(part[1:])
part = self._VAR_NODE
curr_partial_routes = (curr_partial_routes
.setdefault(part, {}))
curr_partial_routes[self._ROUTE_NODE] = _Route(
key_parts=curr_key_parts,
anything=anything)
self._max_depth = max(self._max_depth, depth_of(parts))
|
<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_site_url():
"""Returns a URL for current site. :rtype: str|unicode """
|
site_url = getattr(_THREAD_LOCAL, _THREAD_SITE_URL, None)
if site_url is None:
site_url = SITE_URL or get_site_url_()
setattr(_THREAD_LOCAL, _THREAD_SITE_URL, site_url)
return site_url
|
<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_message_type_for_app(app_name, default_message_type_alias):
"""Returns a registered message type object for a given application. Supposed to be used by reusable applications authors, to get message type objects which may be overridden by project authors using `override_message_type_for_app`. :param str|unicode app_name: :param str|unicode default_message_type_alias: :return: a message type object overridden is so, or the default :rtype: MessageBase """
|
message_type = default_message_type_alias
try:
message_type = _MESSAGES_FOR_APPS[app_name][message_type]
except KeyError:
pass
return get_registered_message_type(message_type)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recipients(messenger, addresses):
"""Structures recipients data. :param str|unicode, MessageBase messenger: MessengerBase heir :param list[str|unicode]|str|unicode addresses: recipients addresses or Django User model heir instances (NOTE: if supported by a messenger) :return: list of Recipient :rtype: list[Recipient] """
|
if isinstance(messenger, six.string_types):
messenger = get_registered_messenger_object(messenger)
return messenger._structure_recipients_data(addresses)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upcoming_live_chat(self):
""" Find any upcoming or current live chat to advertise on the home page or live chat page. These are LiveChat's with primary category of 'ask-mama' and category of 'live-chat'. The Chat date must be less than 5 days away, or happening now. """
|
chat = None
now = datetime.now()
lcqs = self.get_query_set()
lcqs = lcqs.filter(
chat_ends_at__gte=now).order_by('-chat_starts_at')
try:
if settings.LIVECHAT_PRIMARY_CATEGORY:
lcqs = lcqs.filter(
primary_category__slug=settings.LIVECHAT_PRIMARY_CATEGORY)
except AttributeError:
pass
try:
if settings.LIVECHAT_CATEGORIES:
lcqs = lcqs.filter(
categories__slug__in=settings.LIVECHAT_CATEGORIES)
except AttributeError:
pass
if lcqs.exists():
chat = lcqs.latest('chat_starts_at')
return chat
|
<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_current_live_chat(self):
""" Check if there is a live chat on the go, so that we should take over the AskMAMA page with the live chat. """
|
now = datetime.now()
chat = self.upcoming_live_chat()
if chat and chat.is_in_progress():
return chat
return None
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.