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 read(*filenames, **kwargs):
""" Read file contents into string. Used by setup.py to concatenate long_description. :param string filenames: Files to be read and concatenated. :rtype: string """
|
encoding = kwargs.get('encoding', 'utf-8')
sep = kwargs.get('sep', '\n')
buf = []
for filename in filenames:
if path.splitext(filename)[1] == ".md":
try:
import pypandoc
buf.append(pypandoc.convert_file(filename, 'rst'))
continue
except:
with io.open(filename, encoding=encoding) as f:
buf.append(f.read())
with io.open(filename, encoding=encoding) as f:
buf.append(f.read())
return sep.join(buf)
|
<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(cls, pid_type, pid_value, pid_provider=None, status=PIDStatus.NEW, object_type=None, object_uuid=None,):
"""Create a new persistent identifier with specific type and value. :param pid_type: Persistent identifier type. :param pid_value: Persistent identifier value. :param pid_provider: Persistent identifier provider. (default: None). :param status: Current PID status. (Default: :attr:`invenio_pidstore.models.PIDStatus.NEW`) :param object_type: The object type is a string that identify its type. (default: None). :param object_uuid: The object UUID. (default: None). :returns: A :class:`invenio_pidstore.models.PersistentIdentifier` instance. """
|
try:
with db.session.begin_nested():
obj = cls(pid_type=pid_type,
pid_value=pid_value,
pid_provider=pid_provider,
status=status)
if object_type and object_uuid:
obj.assign(object_type, object_uuid)
db.session.add(obj)
logger.info("Created PID {0}:{1}".format(pid_type, pid_value),
extra={'pid': obj})
except IntegrityError:
logger.exception(
"PID already exists: {0}:{1}".format(pid_type, pid_value),
extra=dict(
pid_type=pid_type,
pid_value=pid_value,
pid_provider=pid_provider,
status=status,
object_type=object_type,
object_uuid=object_uuid,
))
raise PIDAlreadyExists(pid_type=pid_type, pid_value=pid_value)
except SQLAlchemyError:
logger.exception(
"Failed to create PID: {0}:{1}".format(pid_type, pid_value),
extra=dict(
pid_type=pid_type,
pid_value=pid_value,
pid_provider=pid_provider,
status=status,
object_type=object_type,
object_uuid=object_uuid,
))
raise
return obj
|
<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(cls, pid_type, pid_value, pid_provider=None):
"""Get persistent identifier. :param pid_type: Persistent identifier type. :param pid_value: Persistent identifier value. :param pid_provider: Persistent identifier provider. (default: None). :raises: :exc:`invenio_pidstore.errors.PIDDoesNotExistError` if no PID is found. :returns: A :class:`invenio_pidstore.models.PersistentIdentifier` instance. """
|
try:
args = dict(pid_type=pid_type, pid_value=six.text_type(pid_value))
if pid_provider:
args['pid_provider'] = pid_provider
return cls.query.filter_by(**args).one()
except NoResultFound:
raise PIDDoesNotExistError(pid_type, pid_value)
|
<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_by_object(cls, pid_type, object_type, object_uuid):
"""Get a persistent identifier for a given object. :param pid_type: Persistent identifier type. :param object_type: The object type is a string that identify its type. :param object_uuid: The object UUID. :raises invenio_pidstore.errors.PIDDoesNotExistError: If no PID is found. :returns: A :class:`invenio_pidstore.models.PersistentIdentifier` instance. """
|
try:
return cls.query.filter_by(
pid_type=pid_type,
object_type=object_type,
object_uuid=object_uuid
).one()
except NoResultFound:
raise PIDDoesNotExistError(pid_type, 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 get_assigned_object(self, object_type=None):
"""Return the current assigned object UUID. :param object_type: If it's specified, returns only if the PID object_type is the same, otherwise returns None. (default: None). :returns: The object UUID. """
|
if object_type is not None:
if self.object_type == object_type:
return self.object_uuid
else:
return None
return self.object_uuid
|
<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(self, object_type, object_uuid, overwrite=False):
"""Assign this persistent identifier to a given object. Note, the persistent identifier must first have been reserved. Also, if an existing object is already assigned to the pid, it will raise an exception unless overwrite=True. :param object_type: The object type is a string that identify its type. :param object_uuid: The object UUID. :param overwrite: Force PID overwrites in case was previously assigned. :raises invenio_pidstore.errors.PIDInvalidAction: If the PID was previously deleted. :raises invenio_pidstore.errors.PIDObjectAlreadyAssigned: If the PID was previously assigned with a different type/uuid. :returns: `True` if the PID is successfully assigned. """
|
if self.is_deleted():
raise PIDInvalidAction(
"You cannot assign objects to a deleted/redirected persistent"
" identifier."
)
if not isinstance(object_uuid, uuid.UUID):
object_uuid = uuid.UUID(object_uuid)
if self.object_type or self.object_uuid:
# The object is already assigned to this pid.
if object_type == self.object_type and \
object_uuid == self.object_uuid:
return True
if not overwrite:
raise PIDObjectAlreadyAssigned(object_type,
object_uuid)
self.unassign()
try:
with db.session.begin_nested():
self.object_type = object_type
self.object_uuid = object_uuid
db.session.add(self)
except SQLAlchemyError:
logger.exception("Failed to assign {0}:{1}".format(
object_type, object_uuid), extra=dict(pid=self))
raise
logger.info("Assigned object {0}:{1}".format(
object_type, object_uuid), extra=dict(pid=self))
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 unassign(self):
"""Unassign the registered object. Note: Only registered PIDs can be redirected so we set it back to registered. :returns: `True` if the PID is successfully unassigned. """
|
if self.object_uuid is None and self.object_type is None:
return True
try:
with db.session.begin_nested():
if self.is_redirected():
db.session.delete(Redirect.query.get(self.object_uuid))
# Only registered PIDs can be redirected so we set it back
# to registered
self.status = PIDStatus.REGISTERED
self.object_type = None
self.object_uuid = None
db.session.add(self)
except SQLAlchemyError:
logger.exception("Failed to unassign object.".format(self),
extra=dict(pid=self))
raise
logger.info("Unassigned object from {0}.".format(self),
extra=dict(pid=self))
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 redirect(self, pid):
"""Redirect persistent identifier to another persistent identifier. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` where redirect the PID. :raises invenio_pidstore.errors.PIDInvalidAction: If the PID is not registered or is not already redirecting to another PID. :raises invenio_pidstore.errors.PIDDoesNotExistError: If PID is not found. :returns: `True` if the PID is successfully redirect. """
|
if not (self.is_registered() or self.is_redirected()):
raise PIDInvalidAction("Persistent identifier is not registered.")
try:
with db.session.begin_nested():
if self.is_redirected():
r = Redirect.query.get(self.object_uuid)
r.pid = pid
else:
with db.session.begin_nested():
r = Redirect(pid=pid)
db.session.add(r)
self.status = PIDStatus.REDIRECTED
self.object_type = None
self.object_uuid = r.id
db.session.add(self)
except IntegrityError:
raise PIDDoesNotExistError(pid.pid_type, pid.pid_value)
except SQLAlchemyError:
logger.exception("Failed to redirect to {0}".format(
pid), extra=dict(pid=self))
raise
logger.info("Redirected PID to {0}".format(pid), extra=dict(pid=self))
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 reserve(self):
"""Reserve the persistent identifier. Note, the reserve method may be called multiple times, even if it was already reserved. :raises: :exc:`invenio_pidstore.errors.PIDInvalidAction` if the PID is not new or is not already reserved a PID. :returns: `True` if the PID is successfully reserved. """
|
if not (self.is_new() or self.is_reserved()):
raise PIDInvalidAction(
"Persistent identifier is not new or reserved.")
try:
with db.session.begin_nested():
self.status = PIDStatus.RESERVED
db.session.add(self)
except SQLAlchemyError:
logger.exception("Failed to reserve PID.", extra=dict(pid=self))
raise
logger.info("Reserved PID.", extra=dict(pid=self))
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 register(self):
"""Register the persistent identifier with the provider. :raises invenio_pidstore.errors.PIDInvalidAction: If the PID is not already registered or is deleted or is a redirection to another PID. :returns: `True` if the PID is successfully register. """
|
if self.is_registered() or self.is_deleted() or self.is_redirected():
raise PIDInvalidAction(
"Persistent identifier has already been registered"
" or is deleted.")
try:
with db.session.begin_nested():
self.status = PIDStatus.REGISTERED
db.session.add(self)
except SQLAlchemyError:
logger.exception("Failed to register PID.", extra=dict(pid=self))
raise
logger.info("Registered PID.", extra=dict(pid=self))
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 delete(self):
"""Delete the persistent identifier. If the persistent identifier haven't been registered yet, it is removed from the database. Otherwise, it's marked as :attr:`invenio_pidstore.models.PIDStatus.DELETED`. :returns: `True` if the PID is successfully removed. """
|
removed = False
try:
with db.session.begin_nested():
if self.is_new():
# New persistent identifier which haven't been registered
# yet.
db.session.delete(self)
removed = True
else:
self.status = PIDStatus.DELETED
db.session.add(self)
except SQLAlchemyError:
logger.exception("Failed to delete PID.", extra=dict(pid=self))
raise
if removed:
logger.info("Deleted PID (removed).", extra=dict(pid=self))
else:
logger.info("Deleted PID.", extra=dict(pid=self))
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 sync_status(self, status):
"""Synchronize persistent identifier status. Used when the provider uses an external service, which might have been modified outside of our system. :param status: The new status to set. :returns: `True` if the PID is successfully sync. """
|
if self.status == status:
return True
try:
with db.session.begin_nested():
self.status = status
db.session.add(self)
except SQLAlchemyError:
logger.exception("Failed to sync status {0}.".format(status),
extra=dict(pid=self))
raise
logger.info("Synced PID status to {0}.".format(status),
extra=dict(pid=self))
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 next(cls):
"""Return next available record identifier."""
|
try:
with db.session.begin_nested():
obj = cls()
db.session.add(obj)
except IntegrityError: # pragma: no cover
with db.session.begin_nested():
# Someone has likely modified the table without using the
# models API. Let's fix the problem.
cls._set_sequence(cls.max())
obj = cls()
db.session.add(obj)
return obj.recid
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def max(cls):
"""Get max record identifier."""
|
max_recid = db.session.query(func.max(cls.recid)).scalar()
return max_recid if max_recid else 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 _set_sequence(cls, val):
"""Internal function to reset sequence to specific value. Note: this function is for PostgreSQL compatibility. :param val: The value to be set. """
|
if db.engine.dialect.name == 'postgresql': # pragma: no cover
db.session.execute(
"SELECT setval(pg_get_serial_sequence("
"'{0}', 'recid'), :newval)".format(
cls.__tablename__), dict(newval=val))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert(cls, val):
"""Insert a record identifier. :param val: The `recid` column value to insert. """
|
with db.session.begin_nested():
obj = cls(recid=val)
db.session.add(obj)
cls._set_sequence(cls.max())
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve(self, pid_value):
"""Resolve a persistent identifier to an internal object. :param pid_value: Persistent identifier. :returns: A tuple containing (pid, object). """
|
pid = PersistentIdentifier.get(self.pid_type, pid_value)
if pid.is_new() or pid.is_reserved():
raise PIDUnregistered(pid)
if pid.is_deleted():
obj_id = pid.get_assigned_object(object_type=self.object_type)
try:
obj = self.object_getter(obj_id) if obj_id else None
except NoResultFound:
obj = None
raise PIDDeletedError(pid, obj)
if pid.is_redirected():
raise PIDRedirectedError(pid, pid.get_redirect())
obj_id = pid.get_assigned_object(object_type=self.object_type)
if not obj_id:
raise PIDMissingObjectError(self.pid_type, pid_value)
return pid, self.object_getter(obj_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 create_sheet(self, title):
""" Create a sheet with the given title. This does not check if another sheet by the same name already exists. """
|
ws = self.conn.sheets_service.AddWorksheet(title, 10, 10, self.id)
self._wsf = None
return Sheet(self, ws)
|
<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(cls, title, conn=None, google_user=None, google_password=None):
""" Open the spreadsheet named ``title``. If no spreadsheet with that name exists, a new one will be created. """
|
spreadsheet = cls.by_title(title, conn=conn, google_user=google_user,
google_password=google_password)
if spreadsheet is None:
spreadsheet = cls.create(title, conn=conn, google_user=google_user,
google_password=google_password)
return spreadsheet
|
<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(cls, title, conn=None, google_user=None, google_password=None):
""" Create a new spreadsheet with the given ``title``. """
|
conn = Connection.connect(conn=conn, google_user=google_user,
google_password=google_password)
res = Resource(type='spreadsheet', title=title)
res = conn.docs_client.CreateResource(res)
id = res.id.text.rsplit('%3A', 1)[-1]
return cls(id, conn, resource=res)
|
<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, id, conn=None, google_user=None, google_password=None):
""" Open a spreadsheet via its resource ID. This is more precise than opening a document by title, and should be used with preference. """
|
conn = Connection.connect(conn=conn, google_user=google_user,
google_password=google_password)
return cls(id=id, conn=conn)
|
<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_title(cls, title, conn=None, google_user=None, google_password=None):
""" Open the first document with the given ``title`` that is returned by document search. """
|
conn = Connection.connect(conn=conn, google_user=google_user,
google_password=google_password)
q = DocsQuery(categories=['spreadsheet'], title=title)
feed = conn.docs_client.GetResources(q=q)
for entry in feed.entry:
if entry.title.text == title:
id = entry.id.text.rsplit('%3A', 1)[-1]
return cls.by_id(id, conn=conn)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_common(app):
"""Post initialization."""
|
if app.config['USERPROFILES_EXTEND_SECURITY_FORMS']:
security_ext = app.extensions['security']
security_ext.confirm_register_form = confirm_register_form_factory(
security_ext.confirm_register_form)
security_ext.register_form = register_form_factory(
security_ext.register_form)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_ui(state):
"""Post initialization for UI application."""
|
app = state.app
init_common(app)
# Register blueprint for templates
app.register_blueprint(
blueprint, url_prefix=app.config['USERPROFILES_PROFILE_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 profile():
"""View for editing a profile."""
|
# Create forms
verification_form = VerificationForm(formdata=None, prefix="verification")
profile_form = profile_form_factory()
# Process forms
form = request.form.get('submit', None)
if form == 'profile':
handle_profile_form(profile_form)
elif form == 'verification':
handle_verification_form(verification_form)
return render_template(
current_app.config['USERPROFILES_PROFILE_TEMPLATE'],
profile_form=profile_form,
verification_form=verification_form,)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def profile_form_factory():
"""Create a profile form."""
|
if current_app.config['USERPROFILES_EMAIL_ENABLED']:
return EmailProfileForm(
formdata=None,
username=current_userprofile.username,
full_name=current_userprofile.full_name,
email=current_user.email,
email_repeat=current_user.email,
prefix='profile', )
else:
return ProfileForm(
formdata=None,
obj=current_userprofile,
prefix='profile', )
|
<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_verification_form(form):
"""Handle email sending verification form."""
|
form.process(formdata=request.form)
if form.validate_on_submit():
send_confirmation_instructions(current_user)
# NOTE: Flash message.
flash(_("Verification email sent."), category="success")
|
<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_profile_form(form):
"""Handle profile update form."""
|
form.process(formdata=request.form)
if form.validate_on_submit():
email_changed = False
with db.session.begin_nested():
# Update profile.
current_userprofile.username = form.username.data
current_userprofile.full_name = form.full_name.data
db.session.add(current_userprofile)
# Update email
if current_app.config['USERPROFILES_EMAIL_ENABLED'] and \
form.email.data != current_user.email:
current_user.email = form.email.data
current_user.confirmed_at = None
db.session.add(current_user)
email_changed = True
db.session.commit()
if email_changed:
send_confirmation_instructions(current_user)
# NOTE: Flash message after successful update of profile.
flash(_('Profile was updated. We have sent a verification '
'email to %(email)s. Please check it.',
email=current_user.email),
category='success')
else:
# NOTE: Flash message after successful update of profile.
flash(_('Profile was updated.'), category='success')
|
<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_errors(self, data):
"""Check for errors on data payload."""
|
if (type(data) == dict and 'status' in data.keys()
and data['status'] == 'failed'):
if data.get('exception_msg') and 'last_id' in data.get('exception_msg'):
raise PyBossaServerNoKeysetPagination
else:
raise Error(data)
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 send_text(self, text):
"""Send text message to telegram user. Text message should be markdown formatted. :param text: markdown formatted text. :return: status code on error. """
|
if not self.is_token_set:
raise ValueError('TelepythClient: Access token is not set!')
stream = StringIO()
stream.write(text)
stream.seek(0)
return self(stream)
|
<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_figure(self, fig, caption=''):
"""Render matplotlib figure into temporary bytes buffer and then send it to telegram user. :param fig: matplotlib figure object. :param caption: text caption of picture. :return: status code on error. """
|
if not self.is_token_set:
raise ValueError('TelepythClient: Access token is not set!')
figure = BytesIO()
fig.savefig(figure, format='png')
figure.seek(0)
parts = [ContentDisposition('caption', caption),
ContentDisposition('figure', figure, filename="figure.png",
content_type='image/png')]
form = MultipartFormData(*parts)
content_type = 'multipart/form-data; boundary=%s' % form.boundary
url = self.base_url + self.access_token
req = Request(url, method='POST')
req.add_header('Content-Type', content_type)
req.add_header('User-Agent', __user_agent__ + '/' + __version__)
req.data = form().read()
res = urlopen(req)
return res.getcode()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prune_clusters(clusters, index, n=3):
""" Delete clusters with fewer than n elements. """
|
torem = set(c for c in clusters if c.size < n)
pruned_clusters = [c for c in clusters if c.size >= n]
terms_torem = []
for term, clusters in index.items():
index[term] = clusters - torem
if len(index[term]) == 0:
terms_torem.append(term)
for t in terms_torem:
del index[t]
return pruned_clusters, index
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def monitor(self, field, callback, poll_interval=None):
""" Monitor `field` for change Will monitor ``field`` for change and execute ``callback`` when change is detected. Example usage:: def handle(resource, field, previous, current):
print "Change from {} to {}".format(previous, current) switch = TapSwitch.objects.get(id=3) # Note that we monitor the entire state of the Hue Tap # switch rather than a specific field switch.monitor(lambda sw: sw.state.as_dict(), handle, poll_interval=0.2) # Execution will stop here and the API client will begin polling for changes hue_api.start_monitor_loop() Args: field (string):
The name of the field to be monitored. This may also be a callable which will be called with the resource instance as its single argument and must return a value which can be compared to previous values. callback (callable):
The callable to be called when a change is detected. It will be called with parameters as follows: * resource instance * field name, * previous value * current value. poll_interval (float):
Interval between polling in seconds. Defaults to the API's `poll_interval` value (which defaults to 0.1 second. Returns: Monitor: """
|
poll_interval = poll_interval or self.api.poll_interval
monitor = self.monitor_class(
resource=self,
field=field,
callback=callback,
poll_interval=poll_interval,
event_queue=self.api.event_queue,
poll_pool=self.api.poll_pool,
)
monitor.start()
return monitor
|
<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_form_factory(Form):
"""Factory for creating an extended user registration form."""
|
class CsrfDisabledProfileForm(ProfileForm):
"""Subclass of ProfileForm to disable CSRF token in the inner form.
This class will always be a inner form field of the parent class
`Form`. The parent will add/remove the CSRF token in the form.
"""
def __init__(self, *args, **kwargs):
"""Initialize the object by hardcoding CSRF token to false."""
kwargs = _update_with_csrf_disabled(kwargs)
super(CsrfDisabledProfileForm, self).__init__(*args, **kwargs)
class RegisterForm(Form):
"""RegisterForm extended with UserProfile details."""
profile = FormField(CsrfDisabledProfileForm, separator='.')
return RegisterForm
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def confirm_register_form_factory(Form):
"""Factory for creating a confirm register form."""
|
class CsrfDisabledProfileForm(ProfileForm):
"""Subclass of ProfileForm to disable CSRF token in the inner form.
This class will always be a inner form field of the parent class
`Form`. The parent will add/remove the CSRF token in the form.
"""
def __init__(self, *args, **kwargs):
"""Initialize the object by hardcoding CSRF token to false."""
kwargs = _update_with_csrf_disabled(kwargs)
super(CsrfDisabledProfileForm, self).__init__(*args, **kwargs)
class ConfirmRegisterForm(Form):
"""RegisterForm extended with UserProfile details."""
profile = FormField(CsrfDisabledProfileForm, separator='.')
return ConfirmRegisterForm
|
<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_with_csrf_disabled(d=None):
"""Update the input dict with CSRF disabled depending on WTF-Form version. From Flask-WTF 0.14.0, `csrf_enabled` param has been deprecated in favor of `meta={csrf: True/False}`. """
|
if d is None:
d = {}
import flask_wtf
from pkg_resources import parse_version
supports_meta = parse_version(flask_wtf.__version__) >= parse_version(
"0.14.0")
if supports_meta:
d.setdefault('meta', {})
d['meta'].update({'csrf': False})
else:
d['csrf_enabled'] = False
return d
|
<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_username(form, field):
"""Wrap username validator for WTForms."""
|
try:
validate_username(field.data)
except ValueError as e:
raise ValidationError(e)
try:
user_profile = UserProfile.get_by_username(field.data)
if current_userprofile.is_anonymous or \
(current_userprofile.user_id != user_profile.user_id and
field.data != current_userprofile.username):
# NOTE: Form validation error.
raise ValidationError(_('Username already exists.'))
except NoResultFound:
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 filter_pages(pages, pagenum, pagename):
""" Choices pages by pagenum and pagename """
|
if pagenum:
try:
pages = [list(pages)[pagenum - 1]]
except IndexError:
raise IndexError('Invalid page number: %d' % pagenum)
if pagename:
pages = [page for page in pages if page.name == pagename]
if pages == []:
raise IndexError('Page not found: pagename=%s' % pagename)
return pages
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export_img(visio_filename, image_filename, pagenum=None, pagename=None):
""" Exports images from visio file """
|
# visio requires absolute path
image_pathname = os.path.abspath(image_filename)
if not os.path.isdir(os.path.dirname(image_pathname)):
msg = 'Could not write image file: %s' % image_filename
raise IOError(msg)
with VisioFile.Open(visio_filename) as visio:
pages = filter_pages(visio.pages, pagenum, pagename)
try:
if len(pages) == 1:
pages[0].Export(image_pathname)
else:
digits = int(log(len(pages), 10)) + 1
basename, ext = os.path.splitext(image_pathname)
filename_format = "%s%%0%dd%s" % (basename, digits, ext)
for i, page in enumerate(pages):
filename = filename_format % (i + 1)
page.Export(filename)
except Exception:
raise IOError('Could not write image: %s' % image_pathname)
|
<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_options(args):
""" Parses command line options """
|
usage = 'usage: %prog [options] visio_filename image_filename'
parser = OptionParser(usage=usage)
parser.add_option('-p', '--page', action='store',
type='int', dest='pagenum',
help='pick a page by page number')
parser.add_option('-n', '--name', action='store',
type='string', dest='pagename',
help='pick a page by page name')
options, argv = parser.parse_args(args)
if options.pagenum and options.pagename:
parser.error('options --page and --name are mutually exclusive')
if len(argv) != 2:
parser.print_usage(sys.stderr)
parser.exit()
output_ext = os.path.splitext(argv[1])[1].lower()
if output_ext not in ('.gif', '.jpg', '.png'):
parser.error('Unsupported image format: %s' % argv[1])
return options, argv
|
<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(args=sys.argv[1:]):
""" main funcion of visio2img """
|
if not is_pywin32_available():
sys.stderr.write('win32com module not found')
return -1
try:
options, argv = parse_options(args)
export_img(argv[0], argv[1], options.pagenum, options.pagename)
return 0
except (IOError, OSError, IndexError) as err:
sys.stderr.write("error: %s" % err)
return -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 get_custom_providers():
"""Imports providers classes by paths given in SITEMETRICS_PROVIDERS setting."""
|
providers = getattr(settings, 'SITEMETRICS_PROVIDERS', False)
if not providers:
return []
p_clss = []
for provider_path in providers:
path_splitted = provider_path.split('.')
mod = import_module('.'.join(path_splitted[:-1]))
p_cls = getattr(mod, path_splitted[-1])
p_clss.append(p_cls)
return p_clss
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __query(cls, url):
"""Reads a URL"""
|
try:
return urllib2.urlopen(url).read().decode('utf-8').replace('\n', '')
except urllib2.HTTPError:
_, exception, _ = sys.exc_info()
if cls.__debug:
print('HTTPError = ' + str(exception.code))
except urllib2.URLError:
_, exception, _ = sys.exc_info()
if cls.__debug:
print('URLError = ' + str(exception.reason))
except Exception:
_, exception, _ = sys.exc_info()
if cls.__debug:
print('generic exception: ' + str(exception))
raise
pass
return "inval"
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __query_cmd(self, command, device=None):
"""Calls a command"""
|
base_url = u'%s&switchcmd=%s' % (self.__homeauto_url_with_sid(), command)
if device is None:
url = base_url
else:
url = '%s&ain=%s' % (base_url, device)
if self.__debug:
print(u'Query Command URI: ' + url)
return self.__query(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_sid(self):
"""Returns a valid SID"""
|
base_url = u'%s/login_sid.lua' % self.__fritz_url
get_challenge = None
try:
get_challenge = urllib2.urlopen(base_url).read().decode('ascii')
except urllib2.HTTPError as exception:
print('HTTPError = ' + str(exception.code))
except urllib2.URLError as exception:
print('URLError = ' + str(exception.reason))
except Exception as exception:
print('generic exception: ' + str(exception))
raise
challenge = get_challenge.split(
'<Challenge>')[1].split('</Challenge>')[0]
challenge_b = (
challenge + '-' + self.__password).encode().decode('iso-8859-1').encode('utf-16le')
md5hash = hashlib.md5()
md5hash.update(challenge_b)
response_b = challenge + '-' + md5hash.hexdigest().lower()
get_sid = urllib2.urlopen('%s?%sresponse=%s' % (base_url, self.__username_query, response_b)).read().decode('utf-8')
self.sid = get_sid.split('<SID>')[1].split('</SID>')[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 switch_onoff(self, device, status):
"""Switch a Socket"""
|
if status == 1 or status == True or status == '1':
return self.switch_on(device)
else:
return self.switch_off(device)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def switch_toggle(self, device):
"""Toggles the current state of the given device"""
|
state = self.get_state(device)
if(state == '1'):
return self.switch_off(device)
elif(state == '0'):
return self.switch_on(device)
else:
return state
|
<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_power(self):
"""Returns the Power in Watt"""
|
power_dict = self.get_power_all()
for device in power_dict.keys():
power_dict[device] = float(power_dict[device]) / 1000.0
return power_dict
|
<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_device_names(self):
"""Returns a Dict with devicenames"""
|
dev_names = {}
for device in self.get_device_ids():
dev_names[device] = self.get_device_name(device)
return dev_names
|
<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_power_all(self):
"""Returns the power in mW for all devices"""
|
power_dict = {}
for device in self.get_device_names().keys():
power_dict[device] = self.get_power_single(device)
return power_dict
|
<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_state_all(self):
"""Returns all device states"""
|
state_dict = {}
for device in self.get_device_names().keys():
state_dict[device] = self.get_state(device)
return state_dict
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_entrypoints(entry_point):
"""List defined entry points."""
|
found_entry_points = {}
for dist in working_set:
entry_map = dist.get_entry_map()
for group_name, entry_points in entry_map.items():
# Filter entry points
if entry_point is None and \
not group_name.startswith('invenio'):
continue
if entry_point is not None and \
entry_point != group_name:
continue
# Store entry points.
if group_name not in found_entry_points:
found_entry_points[group_name] = []
for ep in entry_points.values():
found_entry_points[group_name].append(str(ep))
for ep_group in sorted(found_entry_points.keys()):
click.secho('{0}'.format(ep_group), fg='green')
for ep in sorted(found_entry_points[ep_group]):
click.echo(' {0}'.format(ep))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def migrate_secret_key(old_key):
"""Call entry points exposed for the SECRET_KEY change."""
|
if 'SECRET_KEY' not in current_app.config or \
current_app.config['SECRET_KEY'] is None:
raise click.ClickException(
'SECRET_KEY is not set in the configuration.')
for ep in iter_entry_points('invenio_base.secret_key'):
try:
ep.load()(old_key=old_key)
except Exception:
current_app.logger.error(
'Failed to initialize entry point: {0}'.format(ep))
raise
click.secho('Successfully changed secret key.', fg='green')
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_secret_key():
"""Generate secret key."""
|
import string
import random
rng = random.SystemRandom()
return ''.join(
rng.choice(string.ascii_letters + string.digits)
for dummy in range(0, 256)
)
|
<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_provider_choices():
"""Returns a list of currently available metrics providers suitable for use as model fields choices. """
|
choices = []
for provider in METRICS_PROVIDERS:
choices.append((provider.alias, provider.title))
return choices
|
<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_batch(messages, api_key=None, secure=None, test=None, **request_args):
'''Send a batch of messages.
:param messages: Messages to send.
:type message: A list of `dict` or :class:`Message`
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param \*\*request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`BatchSendResponse`
'''
return _default_pyst_batch_sender.send(messages=messages, api_key=api_key,
secure=secure, test=test,
**request_args)
|
<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_delivery_stats(api_key=None, secure=None, test=None, **request_args):
'''Get delivery stats for your Postmark account.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param \*\*request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`DeliveryStatsResponse`
'''
return _default_delivery_stats.get(api_key=api_key, secure=secure,
test=test, **request_args)
|
<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_bounces(api_key=None, secure=None, test=None, **request_args):
'''Get a paginated list of bounces.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param \*\*request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`BouncesResponse`
'''
return _default_bounces.get(api_key=api_key, secure=secure,
test=test, **request_args)
|
<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_bounce(bounce_id, api_key=None, secure=None, test=None,
**request_args):
'''Get a single bounce.
:param bounce_id: The bounce's id. Get the id with :func:`get_bounces`.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param \*\*request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`BounceResponse`
'''
return _default_bounce.get(bounce_id, api_key=api_key, secure=secure,
test=test, **request_args)
|
<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_bounce_dump(bounce_id, api_key=None, secure=None, test=None,
**request_args):
'''Get the raw email dump for a single bounce.
:param bounce_id: The bounce's id. Get the id with :func:`get_bounces`.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param \*\*request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`BounceDumpResponse`
'''
return _default_bounce_dump.get(bounce_id, api_key=api_key, secure=secure,
test=test, **request_args)
|
<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_bounce_tags(api_key=None, secure=None, test=None, **request_args):
'''Get a list of tags for bounces associated with your Postmark server.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param \*\*request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`BounceTagsResponse`
'''
return _default_bounce_tags.get(api_key=api_key, secure=secure, test=test,
**request_args)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def activate_bounce(bounce_id, api_key=None, secure=None, test=None,
**request_args):
'''Activate a deactivated bounce.
:param bounce_id: The bounce's id. Get the id with :func:`get_bounces`.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmark Test API. Defaults to `False`.
:param \*\*request_args: Keyword arguments to pass to
:func:`requests.request`.
:rtype: :class:`BounceActivateResponse`
'''
return _default_bounce_activate.activate(bounce_id, api_key=api_key,
secure=secure, test=test,
**request_args)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def data(self):
'''Returns data formatted for a POST request to the Postmark send API.
:rtype: `dict`
'''
d = {}
for val, key in self._fields.items():
val = getattr(self, val)
if val is not None:
d[key] = val
return d
|
<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_header(self, name, value):
'''Attach an email header to send with the message.
:param name: The name of the header value.
:param value: The header value.
'''
if self.headers is None:
self.headers = []
self.headers.append(dict(Name=name, Value=value))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def attach_binary(self, data, filename, content_type=None,
content_id=None):
'''Attach a file to the message given raw binary data.
:param data: Raw data to attach to the message.
:param filename: Name of the file for the data.
:param content_type: mimetype of the data. It will be guessed from the
filename if not provided.
:param content_id: ContentID URL of the attachment. A RFC 2392-
compliant URL for the attachment that allows it to be referenced
from inside the body of the message. Must start with 'cid:'
'''
if self.attachments is None:
self.attachments = []
if content_type is None:
content_type = self._detect_content_type(filename)
attachment = {
'Name': filename,
'Content': b64encode(data).decode('utf-8'),
'ContentType': content_type
}
if content_id is not None:
if not content_id.startswith('cid:'):
raise MessageError('content_id parameter must be an '
'RFC-2392 URL starting with "cid:"')
attachment['ContentID'] = content_id
self.attachments.append(attachment)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def attach_file(self, filename, content_type=None,
content_id=None):
'''Attach a file to the message given a filename.
:param filename: Name of the file to attach.
:param content_type: mimetype of the data. It will be guessed from the
filename if not provided.
:param content_id: ContentID URL of the attachment. A RFC 2392-
compliant URL for the attachment that allows it to be referenced
from inside the body of the message. Must start with 'cid:'
'''
# Open the file, grab the filename, detect content type
name = os.path.basename(filename)
if not name:
err = 'Filename not found in path: {0}'
raise MessageError(err.format(filename))
with open(filename, 'rb') as f:
data = f.read()
self.attach_binary(data, name, content_type=content_type,
content_id=content_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 recipients(self):
'''A list of all recipients for this message.
'''
cc = self._cc or []
bcc = self._bcc or []
return self._to + cc + bcc
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def _detect_content_type(self, filename):
'''Determine the mimetype for a file.
:param filename: Filename of file to detect.
'''
name, ext = os.path.splitext(filename)
if not ext:
raise MessageError('File requires an extension.')
ext = ext.lower()
if ext.lstrip('.') in self._banned_extensions:
err = 'Extension "{0}" is not allowed.'
raise MessageError(err.format(ext))
if not mimetypes.inited:
mimetypes.init()
return mimetypes.types_map.get(ext, self._default_content_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 _verify_attachments(self):
'''Verify that attachment values match the format expected by the
Postmark API.
'''
if self.attachments is None:
return
keys = ('Name', 'Content', 'ContentType')
self._verify_dict_list(self.attachments, keys, 'Attachment')
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def _verify_dict_list(self, values, keys, name):
'''Validate a list of `dict`, ensuring it has specific keys
and no others.
:param values: A list of `dict` to validate.
:param keys: A list of keys to validate each `dict` against.
:param name: Name describing the values, to show in error messages.
'''
keys = set(keys)
name = name.title()
for value in values:
if not isinstance(value, Mapping):
raise MessageError('Invalid {0} value'.format(name))
for key in keys:
if key not in value:
err = '{0} must contain "{1}"'
raise MessageError(err.format(name, key))
if set(value) - keys:
err = '{0} must contain only {1}'
words = ['"{0}"'.format(r) for r in sorted(keys)]
words = ' and '.join(words)
raise MessageError(err.format(name, words))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def dump(self, sender=None, **kwargs):
'''Retrieve raw email dump for this bounce.
:param sender: A :class:`BounceDump` object to get dump with.
Defaults to `None`.
:param \*\*kwargs: Keyword arguments passed to
:func:`requests.request`.
'''
if sender is None:
if self._sender is None:
sender = _default_bounce_dump
else:
sender = BounceDump(api_key=self._sender.api_key,
test=self._sender.test,
secure=self._sender.secure)
return sender.get(self.id, **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 raise_for_status(self):
'''Raise Postmark-specific HTTP errors. If there isn't one, the
standard HTTP error is raised.
HTTP 401 raises :class:`UnauthorizedError`
HTTP 422 raises :class:`UnprocessableEntityError`
HTTP 500 raises :class:`InternalServerError`
'''
if self.status_code == 401:
raise UnauthorizedError(self._requests_response)
elif self.status_code == 422:
raise UnprocessableEntityError(self._requests_response)
elif self.status_code == 500:
raise InternalServerError(self._requests_response)
return self._requests_response.raise_for_status()
|
<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_api_url(self, secure=None, **formatters):
'''Constructs Postmark API url
:param secure: Use the https Postmark API.
:param \*\*formatters: :func:`string.format` keyword arguments to
format the url with.
:rtype: Postmark API url
'''
if self.endpoint is None:
raise NotImplementedError('endpoint must be defined on a subclass')
if secure is None:
secure = self.secure
if secure:
api_url = POSTMARK_API_URL_SECURE
else:
api_url = POSTMARK_API_URL
url = urljoin(api_url, self.endpoint)
if formatters:
url = url.format(**formatters)
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 _get_headers(self, api_key=None, test=None, request_args=None):
'''Constructs the headers to use for the request.
:param api_key: Your Postmark API key. Defaults to `None`.
:param test: Use the Postmark test API. Defaults to `self.test`.
:param request_args: Keyword args to pass to :func:`requests.request`.
Defaults to `None`.
:rtype: `dict` of header values.
'''
if request_args is None:
request_args = {}
headers = {}
headers.update(self._headers)
headers.update(request_args.pop('headers', {}))
if (test is None and self.test) or test:
headers[self._api_key_header_name] = POSTMARK_API_TEST_KEY
elif api_key is not None:
headers[self._api_key_header_name] = api_key
else:
headers[self._api_key_header_name] = self.api_key
if not headers.get(self._api_key_header_name):
raise ValueError('Postmark API Key not provided')
return headers
|
<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_request_content(self, message=None):
'''Updates message with default message paramaters.
:param message: Postmark message data
:type message: `dict`
:rtype: JSON encoded `unicode`
'''
message = self._cast_message(message=message)
return message.json()
|
<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_request_content(self, message=None):
'''Updates all messages in message with default message
parameters.
:param message: A collection of Postmark message data
:type message: a collection of message `dict`s
:rtype: JSON encoded `str`
'''
if not message:
raise MessageError('No messages to send.')
if len(message) > MAX_BATCH_MESSAGES:
err = 'Maximum {0} messages allowed in batch'
raise MessageError(err.format(MAX_BATCH_MESSAGES))
message = [self._cast_message(message=msg) for msg in message]
message = [msg.data() for msg in message]
return json.dumps(message, ensure_ascii=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(self, bounce_id, api_key=None, secure=None, test=None,
**request_args):
'''Retrieves a single bounce's data.
:param bounce_id: A bounce's ID retrieved with :class:`Bounces`.
:param api_key: Your Postmark API key. Defaults to `self.api_key`.
:param secure: Use the https scheme for Postmark API.
Defaults to `self.secure`.
:param test: Make a test request to the Postmark API.
Defaults to `self.test`.
:param \*\*request_args: Keyword args to pass to
:func:`requests.request`.
:rtype: :class:`BounceResponse`
'''
url = self._get_api_url(secure=secure, bounce_id=bounce_id)
headers = self._get_headers(api_key=api_key, test=test,
request_args=request_args)
return self._request(url, headers=headers, **request_args)
|
<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_app_factory(app_name, config_loader=None, extension_entry_points=None, extensions=None, blueprint_entry_points=None, blueprints=None, converter_entry_points=None, converters=None, wsgi_factory=None, **app_kwargs):
"""Create a Flask application factory. The application factory will load Flask extensions and blueprints specified using both entry points and directly in the arguments. Loading order of entry points are not guaranteed and can happen in any order. :param app_name: Flask application name. :param config_loader: Callable which will be invoked on application creation in order to load the Flask configuration. See example below. :param extension_entry_points: List of entry points, which specifies Flask extensions that will be initialized only by passing in the Flask application object :param extensions: List of Flask extensions that can be initialized only by passing in the Flask application object. :param blueprint_entry_points: List of entry points, which specifies Blueprints that will be registered on the Flask application. :param blueprints: List of Blueprints that will be registered on the Flask application. :param converter_entry_points: List of entry points, which specifies Werkzeug URL map converters that will be added to ``app.url_map.converters``. :param converters: Map of Werkzeug URL map converter classes that will be added to ``app.url_map.converters``. :param wsgi_factory: A callable that will be passed the Flask application object in order to overwrite the default WSGI application (e.g. to install ``DispatcherMiddleware``). :param app_kwargs: Keyword arguments passed to :py:meth:`base_app`. :returns: Flask application factory. Example of a configuration loader: .. code-block:: python def my_config_loader(app, **kwargs):
app.config.from_module('mysite.config') app.config.update(**kwargs) .. note:: `Invenio-Config <https://pythonhosted.org/invenio-config>`_ provides a factory creating default configuration loader (see :func:`invenio_config.utils.create_config_loader`) which is sufficient for most cases. Example of a WSGI factory: .. code-block:: python def my_wsgi_factory(app):
return DispatcherMiddleware(app.wsgi_app, {'/api': api_app}) .. versionadded: 1.0.0 """
|
def _create_app(**kwargs):
app = base_app(app_name, **app_kwargs)
app_created.send(_create_app, app=app)
debug = kwargs.get('debug')
if debug is not None:
app.debug = debug
# Load configuration
if config_loader:
config_loader(app, **kwargs)
# Load URL converters.
converter_loader(
app,
entry_points=converter_entry_points,
modules=converters,
)
# Load application based on entrypoints.
app_loader(
app,
entry_points=extension_entry_points,
modules=extensions,
)
# Load blueprints
blueprint_loader(
app,
entry_points=blueprint_entry_points,
modules=blueprints,
)
app_loaded.send(_create_app, app=app)
# Replace WSGI application using factory if provided (e.g. to install
# WSGI middleware).
if wsgi_factory:
app.wsgi_app = wsgi_factory(app, **kwargs)
return app
return _create_app
|
<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_cli(create_app=None):
"""Create CLI for ``inveniomanage`` command. :param create_app: Flask application factory. :returns: Click command group. .. versionadded: 1.0.0 """
|
def create_cli_app(info):
"""Application factory for CLI app.
Internal function for creating the CLI. When invoked via
``inveniomanage`` FLASK_APP must be set.
"""
if create_app is None:
# Fallback to normal Flask behavior
info.create_app = None
app = info.load_app()
else:
app = create_app(debug=get_debug_flag())
return app
@click.group(cls=FlaskGroup, create_app=create_cli_app)
def cli(**params):
"""Command Line Interface for Invenio."""
pass
return cli
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def app_loader(app, entry_points=None, modules=None):
"""Run default application loader. :param entry_points: List of entry points providing to Flask extensions. :param modules: List of Flask extensions. .. versionadded: 1.0.0 """
|
_loader(app, lambda ext: ext(app), entry_points=entry_points,
modules=modules)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def blueprint_loader(app, entry_points=None, modules=None):
"""Run default blueprint loader. The value of any entry_point or module passed can be either an instance of ``flask.Blueprint`` or a callable accepting a ``flask.Flask`` application instance as a single argument and returning an instance of ``flask.Blueprint``. :param entry_points: List of entry points providing to Blueprints. :param modules: List of Blueprints. .. versionadded: 1.0.0 """
|
url_prefixes = app.config.get('BLUEPRINTS_URL_PREFIXES', {})
def loader_init_func(bp_or_func):
bp = bp_or_func(app) if callable(bp_or_func) else bp_or_func
app.register_blueprint(bp, url_prefix=url_prefixes.get(bp.name))
_loader(app, loader_init_func, entry_points=entry_points, modules=modules)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def converter_loader(app, entry_points=None, modules=None):
"""Run default converter loader. :param entry_points: List of entry points providing to Blue. :param modules: Map of coverters. .. versionadded: 1.0.0 """
|
if entry_points:
for entry_point in entry_points:
for ep in pkg_resources.iter_entry_points(entry_point):
try:
app.url_map.converters[ep.name] = ep.load()
except Exception:
app.logger.error(
'Failed to initialize entry point: {0}'.format(ep))
raise
if modules:
app.url_map.converters.update(**modules)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _loader(app, init_func, entry_points=None, modules=None):
"""Run generic loader. Used to load and initialize entry points and modules using an custom initialization function. .. versionadded: 1.0.0 """
|
if entry_points:
for entry_point in entry_points:
for ep in pkg_resources.iter_entry_points(entry_point):
try:
init_func(ep.load())
except Exception:
app.logger.error(
'Failed to initialize entry point: {0}'.format(ep))
raise
if modules:
for m in modules:
try:
init_func(m)
except Exception:
app.logger.error('Failed to initialize module: {0}'.format(m))
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 base_app(import_name, instance_path=None, static_folder=None, static_url_path='/static', template_folder='templates', instance_relative_config=True, app_class=Flask):
"""Invenio base application factory. If the instance folder does not exists, it will be created. :param import_name: The name of the application package. :param env_prefix: Environment variable prefix. :param instance_path: Instance path for Flask application. :param static_folder: Static folder path. :param app_class: Flask application class. :returns: Flask application instance. .. versionadded: 1.0.0 """
|
configure_warnings()
# Create the Flask application instance
app = app_class(
import_name,
instance_path=instance_path,
instance_relative_config=instance_relative_config,
static_folder=static_folder,
static_url_path=static_url_path,
template_folder=template_folder,
)
# Create instance path if it doesn't exists
try:
if instance_path and not os.path.exists(instance_path):
os.makedirs(instance_path)
except Exception: # pragma: no cover
app.logger.exception(
'Failed to create instance folder: "{0}"'.format(instance_path)
)
return app
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure_warnings():
"""Configure warnings by routing warnings to the logging system. It also unhides ``DeprecationWarning``. .. versionadded: 1.0.0 """
|
if not sys.warnoptions:
# Route warnings through python logging
logging.captureWarnings(True)
# DeprecationWarning is by default hidden, hence we force the
# 'default' behavior on deprecation warnings which is not to hide
# errors.
warnings.simplefilter('default', DeprecationWarning)
warnings.simplefilter('ignore', PendingDeprecationWarning)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def config_loader(app, **kwargs):
"""Custom config loader."""
|
app.config.from_object(Config)
app.config.update(**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 get_project(self, project_short_name):
"""Return project object."""
|
project = pbclient.find_project(short_name=project_short_name,
all=self.all)
if (len(project) == 1):
return project[0]
else:
raise ProjectNotFound(project_short_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 get_tasks(self, task_id=None, state='completed', json_file=None):
"""Load all project Tasks."""
|
if self.project is None:
raise ProjectError
loader = create_tasks_loader(self.project.id, task_id,
state, json_file, self.all)
self.tasks = loader.load()
self._check_project_has_tasks()
self.tasks_df = dataframer.create_data_frame(self.tasks)
|
<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_task_runs(self, json_file=None):
"""Load all project Task Runs from Tasks."""
|
if self.project is None:
raise ProjectError
loader = create_task_runs_loader(self.project.id, self.tasks,
json_file, self.all)
self.task_runs, self.task_runs_file = loader.load()
self._check_project_has_taskruns()
self.task_runs_df = dataframer.create_task_run_data_frames(self.tasks, self.task_runs)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe(self, element):
# pragma: no cover """Return tasks or task_runs Panda describe."""
|
if (element == 'tasks'):
return self.tasks_df.describe()
elif (element == 'task_runs'):
return self.task_runs_df.describe()
else:
return "ERROR: %s not found" % element
|
<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_wsgi_factory(mounts_factories):
"""Create a WSGI application factory. Usage example: .. code-block:: python wsgi_factory = create_wsgi_factory({'/api': create_api}) :param mounts_factories: Dictionary of mount points per application factory. .. versionadded:: 1.0.0 """
|
def create_wsgi(app, **kwargs):
mounts = {
mount: factory(**kwargs)
for mount, factory in mounts_factories.items()
}
return DispatcherMiddleware(app.wsgi_app, mounts)
return create_wsgi
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wsgi_proxyfix(factory=None):
"""Fix ``REMOTE_ADDR`` based on ``X-Forwarded-For`` headers. .. note:: You must set ``WSGI_PROXIES`` to the correct number of proxies, otherwise you application is susceptible to malicious attacks. .. versionadded:: 1.0.0 """
|
def create_wsgi(app, **kwargs):
wsgi_app = factory(app, **kwargs) if factory else app.wsgi_app
if app.config.get('WSGI_PROXIES'):
return ProxyFix(wsgi_app, num_proxies=app.config['WSGI_PROXIES'])
return wsgi_app
return create_wsgi
|
<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_migration_files(self):
"""Find migrations files."""
|
migrations = (re.match(MigrationFile.PATTERN, filename)
for filename in os.listdir(self.directory))
migrations = (MigrationFile(m.group('id'), m.group(0))
for m in migrations if m)
return sorted(migrations, key=lambda m: m.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 get_unregistered_migrations(self):
"""Find unregistered migrations."""
|
return [m for m in self.get_migration_files()
if not self.collection.find_one({'filename': m.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 check_directory(self):
"""Check if migrations directory exists."""
|
exists = os.path.exists(self.directory)
if not exists:
logger.error("No migrations directory found. Check your path or create a migration first.")
logger.error("Directory: %s" % self.directory)
return exists
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_status(self):
"""Show status of unregistered migrations"""
|
if not self.check_directory():
return
migrations = self.get_unregistered_migrations()
if migrations:
logger.info('Unregistered migrations:')
for migration in migrations:
logger.info(migration.filename)
else:
logger.info(self.NO_MIGRATIONS_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 get_new_filename(self, name):
"""Generate filename for new migration."""
|
name = MigrationFile.normalize_name(name)
migrations = self.get_migration_files()
migration_id = migrations[-1].id if migrations else 0
migration_id += 1
return '{:04}_{}.py'.format(migration_id, 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 create(self, name):
"""Create a new empty migration."""
|
if not os.path.exists(self.directory):
os.makedirs(self.directory)
filename = self.get_new_filename(name)
with open(os.path.join(self.directory, filename), 'w') as fp:
fp.write("def up(db): pass\n\n\n")
fp.write("def down(db): pass\n")
logger.info(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 load_migration_file(self, filename):
"""Load migration file as module."""
|
path = os.path.join(self.directory, filename)
# spec = spec_from_file_location("migration", path)
# module = module_from_spec(spec)
# spec.loader.exec_module(module)
module = imp.load_source("migration", path)
return module
|
<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_migrations_to_up(self, migration_id=None):
"""Find migrations to execute."""
|
if migration_id is not None:
migration_id = MigrationFile.validate_id(migration_id)
if not migration_id:
return []
migrations = self.get_unregistered_migrations()
if not migrations:
logger.info(self.NO_MIGRATIONS_MSG)
return []
if migration_id:
try:
last_migration = [m for m in migrations
if m.id == migration_id][0]
except IndexError:
logger.error('Migration is not in unregistered list: %s'
% migration_id)
self.show_status()
return []
else:
last_migration = list(migrations)[-1]
return [m for m in migrations if m.id <= last_migration.id]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.