_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q21100
|
setDefaults
|
train
|
def setDefaults(self, instance):
"""Only call during object initialization, this function sets fields
to schema defaults. It's adapted from the original to support
IAcquireFieldDefaults adapters. If IAcquireFieldDefaults adapter
does not find a suitable field, or that field's value is Falseish,
this function will not continue with the normal default machinery.
"""
for field in self.values():
# ## bika addition: we fire adapters for IAcquireFieldDefaults.
# If IAcquireFieldDefaults returns None, this signifies "ignore" return.
# First adapter found with non-None result, wins.
value = None
if shasattr(field, 'acquire'):
adapters = {}
for adapter in getAdapters((instance,), IAcquireFieldDefaults):
sort_val = getattr(adapter[1], 'sort', 1000)
if sort_val not in adapters:
adapters[sort_val] = []
adapters[sort_val].append(adapter)
if adapters:
keys = sorted(adapters.keys())
keys.reverse()
adapter = adapters[keys[0]]
_value = adapter[0][1](field)
if _value is not None:
value = _value
if field.getName().lower() == 'id':
continue
# If our adapter reflects a value for a reference field, it will
# be permitted.
if field.type == "reference" and not value:
continue
default = value if value else field.getDefault(instance)
# always set defaults on writable fields
mutator = field.getMutator(instance)
if mutator is None:
continue
args = (default,)
kw = {'field': field.__name__,
'_initializing_': True}
if shasattr(field, 'default_content_type'):
# specify a mimetype if the mutator takes a mimetype argument if
# the schema supplies a default, we honour that, otherwise we use
# the site property
default_content_type = field.default_content_type
if default_content_type is None:
default_content_type = getDefaultContentType(instance)
kw['mimetype'] = default_content_type
mapply(mutator, *args, **kw)
|
python
|
{
"resource": ""
}
|
q21101
|
do_action_to_ancestors
|
train
|
def do_action_to_ancestors(analysis_request, transition_id):
"""Promotes the transitiion passed in to ancestors, if any
"""
parent_ar = analysis_request.getParentAnalysisRequest()
if parent_ar:
do_action_for(parent_ar, transition_id)
|
python
|
{
"resource": ""
}
|
q21102
|
do_action_to_descendants
|
train
|
def do_action_to_descendants(analysis_request, transition_id):
"""Cascades the transition passed in to the descendant partitions
"""
for partition in analysis_request.getDescendants(all_descendants=False):
do_action_for(partition, transition_id)
|
python
|
{
"resource": ""
}
|
q21103
|
do_action_to_analyses
|
train
|
def do_action_to_analyses(analysis_request, transition_id, all_analyses=False):
"""Cascades the transition to the analysis request analyses. If all_analyses
is set to True, the transition will be triggered for all analyses of this
analysis request, those from the descendant partitions included.
"""
analyses = list()
if all_analyses:
analyses = analysis_request.getAnalyses(full_objects=True)
else:
analyses = analysis_request.objectValues("Analysis")
for analysis in analyses:
do_action_for(analysis, transition_id)
|
python
|
{
"resource": ""
}
|
q21104
|
ajaxGetImportTemplate.getAnalysisServicesDisplayList
|
train
|
def getAnalysisServicesDisplayList(self):
''' Returns a Display List with the active Analysis Services
available. The value is the keyword and the title is the
text to be displayed.
'''
bsc = getToolByName(self, 'bika_setup_catalog')
items = [('', '')] + [(o.getObject().Keyword, o.Title) for o in
bsc(portal_type = 'AnalysisService',
is_active = True)]
items.sort(lambda x, y: cmp(x[1].lower(), y[1].lower()))
return DisplayList(list(items))
|
python
|
{
"resource": ""
}
|
q21105
|
bika_idserver.generate_id
|
train
|
def generate_id(self, portal_type, batch_size = None):
""" Generate a new id for 'portal_type'
"""
plone = getSite()
portal_id = plone.getId()
if portal_type == 'News Item':
portal_type = 'NewsItem'
idserver_url = os.environ.get('IDServerURL')
try:
if batch_size:
# GET
f = urllib.urlopen('%s/%s%s?%s' % (
idserver_url,
portal_id,
portal_type,
urllib.urlencode({'batch_size': batch_size}))
)
else:
f = urllib.urlopen('%s/%s%s' % (
idserver_url, portal_id, portal_type
)
)
id = f.read()
f.close()
except:
from sys import exc_info
info = exc_info()
import zLOG; zLOG.LOG('INFO', 0, '', 'generate_id raised exception: %s, %s \n idserver_url: %s' % (info[0], info[1], idserver_url))
raise IDServerUnavailable(_('ID Server unavailable'))
return id
|
python
|
{
"resource": ""
}
|
q21106
|
Sample.getAnalyses
|
train
|
def getAnalyses(self, contentFilter=None, **kwargs):
""" return list of all analyses against this sample
"""
# contentFilter and kwargs are combined. They both exist for
# compatibility between the two signatures; kwargs has been added
# to be compatible with how getAnalyses() is used everywhere else.
cf = contentFilter if contentFilter else {}
cf.update(kwargs)
analyses = []
for ar in self.getAnalysisRequests():
analyses.extend(ar.getAnalyses(**cf))
return analyses
|
python
|
{
"resource": ""
}
|
q21107
|
Sample.disposal_date
|
train
|
def disposal_date(self):
"""Returns the date the retention period ends for this sample based on
the retention period from the Sample Type. If the sample hasn't been
collected yet, returns None
"""
date_sampled = self.getDateSampled()
if not date_sampled:
return None
# TODO Preservation - preservation's retention period has priority over
# sample type's preservation period
retention_period = self.getSampleType().getRetentionPeriod() or {}
retention_period_delta = timedelta(
days=int(retention_period.get("days", 0)),
hours=int(retention_period.get("hours", 0)),
minutes=int(retention_period.get("minutes", 0))
)
return dt2DT(DT2dt(date_sampled) + retention_period_delta)
|
python
|
{
"resource": ""
}
|
q21108
|
Contact.getContactByUsername
|
train
|
def getContactByUsername(cls, username):
"""Convenience Classmethod which returns a Contact by a Username
"""
# Check if the User is linked already
pc = api.portal.get_tool("portal_catalog")
contacts = pc(portal_type=cls.portal_type,
getUsername=username)
# No Contact assigned to this username
if len(contacts) == 0:
return None
# Multiple Users assigned, this should never happen
if len(contacts) > 1:
logger.error("User '{}' is bound to multiple Contacts '{}'".format(
username, ",".join(map(lambda c: c.Title, contacts))))
return map(lambda x: x.getObject(), contacts)
# Return the found Contact object
return contacts[0].getObject()
|
python
|
{
"resource": ""
}
|
q21109
|
Contact.getUser
|
train
|
def getUser(self):
"""Returns the linked Plone User or None
"""
username = self.getUsername()
if not username:
return None
user = api.user.get(userid=username)
return user
|
python
|
{
"resource": ""
}
|
q21110
|
Contact.setUser
|
train
|
def setUser(self, user_or_username):
"""Link the user to the Contact
:returns: True if OK, False if the User could not be linked
:rtype: bool
"""
user = None
userid = None
# Handle User IDs (strings)
if isinstance(user_or_username, types.StringTypes):
userid = user_or_username
user = api.user.get(userid)
# Handle User Objects (MemberData/PloneUser)
if hasattr(user_or_username, "getId"):
userid = user_or_username.getId()
user = user_or_username
# Not a valid user
if user is None:
return False
# Link the User
return self._linkUser(user)
|
python
|
{
"resource": ""
}
|
q21111
|
Contact.unlinkUser
|
train
|
def unlinkUser(self, delete=False):
"""Unlink the user to the Contact
:returns: True if OK, False if no User was unlinked
:rtype: bool
"""
userid = self.getUsername()
user = self.getUser()
if user:
logger.debug("Unlinking User '{}' from Contact '{}'".format(
userid, self.Title()))
# Unlink the User
if not self._unlinkUser():
return False
# Also remove the Plone User (caution)
if delete:
logger.debug("Removing Plone User '{}'".format(userid))
api.user.delete(username=userid)
return True
return False
|
python
|
{
"resource": ""
}
|
q21112
|
Contact._linkUser
|
train
|
def _linkUser(self, user):
"""Set the UID of the current Contact in the User properties and update
all relevant own properties.
"""
KEY = "linked_contact_uid"
username = user.getId()
contact = self.getContactByUsername(username)
# User is linked to another contact (fix in UI)
if contact and contact.UID() != self.UID():
raise ValueError("User '{}' is already linked to Contact '{}'"
.format(username, contact.Title()))
# User is linked to multiple other contacts (fix in Data)
if isinstance(contact, list):
raise ValueError("User '{}' is linked to multiple Contacts: '{}'"
.format(username, ",".join(
map(lambda x: x.Title(), contact))))
# XXX: Does it make sense to "remember" the UID as a User property?
tool = user.getTool()
try:
user.getProperty(KEY)
except ValueError:
logger.info("Adding User property {}".format(KEY))
tool.manage_addProperty(KEY, "", "string")
# Set the UID as a User Property
uid = self.UID()
user.setMemberProperties({KEY: uid})
logger.info("Linked Contact UID {} to User {}".format(
user.getProperty(KEY), username))
# Set the Username
self.setUsername(user.getId())
# Update the Email address from the user
self.setEmailAddress(user.getProperty("email"))
# somehow the `getUsername` index gets out of sync
self.reindexObject()
# N.B. Local owner role and client group applies only to client
# contacts, but not lab contacts.
if IClient.providedBy(self.aq_parent):
# Grant local Owner role
self._addLocalOwnerRole(username)
# Add user to "Clients" group
self._addUserToGroup(username, group="Clients")
return True
|
python
|
{
"resource": ""
}
|
q21113
|
Contact._unlinkUser
|
train
|
def _unlinkUser(self):
"""Remove the UID of the current Contact in the User properties and
update all relevant own properties.
"""
KEY = "linked_contact_uid"
# Nothing to do if no user is linked
if not self.hasUser():
return False
user = self.getUser()
username = user.getId()
# Unset the UID from the User Property
user.setMemberProperties({KEY: ""})
logger.info("Unlinked Contact UID from User {}"
.format(user.getProperty(KEY, "")))
# Unset the Username
self.setUsername(None)
# Unset the Email
self.setEmailAddress(None)
# somehow the `getUsername` index gets out of sync
self.reindexObject()
# N.B. Local owner role and client group applies only to client
# contacts, but not lab contacts.
if IClient.providedBy(self.aq_parent):
# Revoke local Owner role
self._delLocalOwnerRole(username)
# Remove user from "Clients" group
self._delUserFromGroup(username, group="Clients")
return True
|
python
|
{
"resource": ""
}
|
q21114
|
Contact._addUserToGroup
|
train
|
def _addUserToGroup(self, username, group="Clients"):
"""Add user to the goup
"""
portal_groups = api.portal.get_tool("portal_groups")
group = portal_groups.getGroupById('Clients')
group.addMember(username)
|
python
|
{
"resource": ""
}
|
q21115
|
Contact._delUserFromGroup
|
train
|
def _delUserFromGroup(self, username, group="Clients"):
"""Remove user from the group
"""
portal_groups = api.portal.get_tool("portal_groups")
group = portal_groups.getGroupById(group)
group.removeMember(username)
|
python
|
{
"resource": ""
}
|
q21116
|
Contact._addLocalOwnerRole
|
train
|
def _addLocalOwnerRole(self, username):
"""Add local owner role from parent object
"""
parent = self.getParent()
if parent.portal_type == "Client":
parent.manage_setLocalRoles(username, ["Owner", ])
# reindex object security
self._recursive_reindex_object_security(parent)
|
python
|
{
"resource": ""
}
|
q21117
|
Contact._delLocalOwnerRole
|
train
|
def _delLocalOwnerRole(self, username):
"""Remove local owner role from parent object
"""
parent = self.getParent()
if parent.portal_type == "Client":
parent.manage_delLocalRoles([username])
# reindex object security
self._recursive_reindex_object_security(parent)
|
python
|
{
"resource": ""
}
|
q21118
|
Contact._recursive_reindex_object_security
|
train
|
def _recursive_reindex_object_security(self, obj):
"""Reindex object security after user linking
"""
if hasattr(aq_base(obj), "objectValues"):
for obj in obj.objectValues():
self._recursive_reindex_object_security(obj)
logger.debug("Reindexing object security for {}".format(repr(obj)))
obj.reindexObjectSecurity()
|
python
|
{
"resource": ""
}
|
q21119
|
deprecated
|
train
|
def deprecated(comment=None, replacement=None):
"""Flags a function as deprecated. A warning will be emitted.
:param comment: A human-friendly string, such as 'This function
will be removed soon'
:type comment: string
:param replacement: The function to be used instead
:type replacement: string or function
"""
def decorator(func):
def wrapper(*args, **kwargs):
message = "Call to deprecated function '{}.{}'".format(
func.__module__,
func.__name__)
if replacement and isinstance(replacement, str):
message += ". Use '{}' instead".format(replacement)
elif replacement:
message += ". Use '{}.{}' instead".format(
replacement.__module__,
replacement.__name__)
if comment:
message += ". {}".format(comment)
warnings.simplefilter('always', DeprecationWarning)
warnings.warn(message, category=DeprecationWarning, stacklevel=2)
warnings.simplefilter('default', DeprecationWarning)
return func(*args, **kwargs)
return wrapper
return decorator
|
python
|
{
"resource": ""
}
|
q21120
|
HeaderTableView.get_field_visibility_mode
|
train
|
def get_field_visibility_mode(self, field):
"""Returns "view" or "edit" modes, together with the place within where
this field has to be rendered, based on the permissions the current
user has for the context and the field passed in
"""
fallback_mode = ("hidden", "hidden")
widget = field.widget
# TODO This needs to be done differently
# Check where the field has to be located
layout = widget.isVisible(self.context, "header_table")
if layout in ["invisible", "hidden"]:
return fallback_mode
# Check permissions. We want to display field (either in view or edit
# modes) only if the current user has enough privileges.
if field.checkPermission("edit", self.context):
mode = "edit"
sm = getSecurityManager()
if not sm.checkPermission(ModifyPortalContent, self.context):
logger.warn("Permission '{}' granted for the edition of '{}', "
"but 'Modify portal content' not granted"
.format(field.write_permission, field.getName()))
elif field.checkPermission("view", self.context):
mode = "view"
else:
return fallback_mode
# Check if the field needs to be displayed or not, even if the user has
# the permissions for edit or view. This may depend on criteria other
# than permissions (e.g. visibility depending on a setup setting, etc.)
if widget.isVisible(self.context, mode, field=field) != "visible":
if mode == "view":
return fallback_mode
# The field cannot be rendered in edit mode, but maybe can be
# rendered in view mode.
mode = "view"
if widget.isVisible(self.context, mode, field=field) != "visible":
return fallback_mode
return (mode, layout)
|
python
|
{
"resource": ""
}
|
q21121
|
WorksheetTemplate.getInstruments
|
train
|
def getInstruments(self):
"""Get the allowed instruments
"""
query = {"portal_type": "Instrument", "is_active": True}
if self.getRestrictToMethod():
query.update({
"getMethodUIDs": {
"query": api.get_uid(self.getRestrictToMethod()),
"operator": "or",
}
})
instruments = api.search(query, "bika_setup_catalog")
items = map(lambda i: (i.UID, i.Title), instruments)
instrument = self.getInstrument()
if instrument:
instrument_uids = map(api.get_uid, instruments)
if api.get_uid(instrument) not in instrument_uids:
items.append(
(api.get_uid(instrument), api.get_title(instrument)))
items.sort(lambda x, y: cmp(x[1], y[1]))
items.insert(0, ("", _("No instrument")))
return DisplayList(list(items))
|
python
|
{
"resource": ""
}
|
q21122
|
WorksheetTemplate._getMethodsVoc
|
train
|
def _getMethodsVoc(self):
"""Return the registered methods as DisplayList
"""
methods = api.search({
"portal_type": "Method",
"is_active": True
}, "bika_setup_catalog")
items = map(lambda m: (api.get_uid(m), api.get_title(m)), methods)
items.sort(lambda x, y: cmp(x[1], y[1]))
items.insert(0, ("", _("Not specified")))
return DisplayList(list(items))
|
python
|
{
"resource": ""
}
|
q21123
|
RequestContextAware.redirect
|
train
|
def redirect(self, redirect_url=None, message=None, level="info"):
"""Redirect with a message
"""
if redirect_url is None:
redirect_url = self.back_url
if message is not None:
self.add_status_message(message, level)
return self.request.response.redirect(redirect_url)
|
python
|
{
"resource": ""
}
|
q21124
|
RequestContextAware.get_uids
|
train
|
def get_uids(self):
"""Returns a uids list of the objects this action must be performed
against to. If no values for uids param found in the request, returns
the uid of the current context
"""
uids = self.get_uids_from_request()
if not uids and api.is_object(self.context):
uids = [api.get_uid(self.context)]
return uids
|
python
|
{
"resource": ""
}
|
q21125
|
RequestContextAware.get_uids_from_request
|
train
|
def get_uids_from_request(self):
"""Returns a list of uids from the request
"""
uids = self.request.get("uids", "")
if isinstance(uids, basestring):
uids = uids.split(",")
unique_uids = collections.OrderedDict().fromkeys(uids).keys()
return filter(api.is_uid, unique_uids)
|
python
|
{
"resource": ""
}
|
q21126
|
RequestContextAware.get_action
|
train
|
def get_action(self):
"""Returns the action to be taken from the request. Returns None if no
action is found
"""
action = self.request.get("workflow_action_id", None)
action = self.request.get("workflow_action", action)
if not action:
return None
# A condition in the form causes Plone to sometimes send two actions
# This usually happens when the previous action was not managed properly
# and the request was not able to complete, so the previous form value
# is kept, together with the new one.
if type(action) in (list, tuple):
actions = list(set(action))
if len(actions) > 0:
logger.warn("Multiple actions in request: {}. Fallback to '{}'"
.format(repr(actions), actions[-1]))
action = actions[-1]
return action
|
python
|
{
"resource": ""
}
|
q21127
|
WorkflowActionGenericAdapter.do_action
|
train
|
def do_action(self, action, objects):
"""Performs the workflow transition passed in and returns the list of
objects that have been successfully transitioned
"""
transitioned = []
ActionHandlerPool.get_instance().queue_pool()
for obj in objects:
obj = api.get_object(obj)
success, message = do_action_for(obj, action)
if success:
transitioned.append(obj)
ActionHandlerPool.get_instance().resume()
return transitioned
|
python
|
{
"resource": ""
}
|
q21128
|
WorkflowActionGenericAdapter.success
|
train
|
def success(self, objects, message=None):
"""Redirects the user to success page with informative message
"""
if self.is_context_only(objects):
return self.redirect(message=_("Changes saved."))
ids = map(api.get_id, objects)
if not message:
message = _("Saved items: {}").format(", ".join(ids))
return self.redirect(message=message)
|
python
|
{
"resource": ""
}
|
q21129
|
WorkflowActionGenericAdapter.get_form_value
|
train
|
def get_form_value(self, form_key, object_brain_uid, default=None):
"""Returns a value from the request's form for the given uid, if any
"""
if form_key not in self.request.form:
return default
uid = object_brain_uid
if not api.is_uid(uid):
uid = api.get_uid(object_brain_uid)
values = self.request.form.get(form_key)
if isinstance(values, list):
if len(values) == 0:
return default
if len(values) > 1:
logger.warn("Multiple set of values for {}".format(form_key))
values = values[0]
return values.get(uid, default)
|
python
|
{
"resource": ""
}
|
q21130
|
HistoryAwareReferenceField.get_versioned_references_for
|
train
|
def get_versioned_references_for(self, instance):
"""Returns the versioned references for the given instance
"""
vrefs = []
# Retrieve the referenced objects
refs = instance.getRefs(relationship=self.relationship)
ref_versions = getattr(instance, REFERENCE_VERSIONS, None)
# No versions stored, return the original references
if ref_versions is None:
return refs
for ref in refs:
uid = api.get_uid(ref)
# get the linked version to the reference
version = ref_versions.get(uid)
# append the versioned reference
vrefs.append(self.retrieve_version(ref, version))
return vrefs
|
python
|
{
"resource": ""
}
|
q21131
|
HistoryAwareReferenceField.retrieve_version
|
train
|
def retrieve_version(self, obj, version):
"""Retrieve the version of the object
"""
current_version = getattr(obj, VERSION_ID, None)
if current_version is None:
# No initial version
return obj
if str(current_version) == str(version):
# Same version
return obj
# Retrieve the object from the repository
pr = api.get_tool("portal_repository")
# bypass permission check to AccessPreviousVersions
result = pr._retrieve(
obj, selector=version, preserve=(), countPurged=True)
return result.object
|
python
|
{
"resource": ""
}
|
q21132
|
HistoryAwareReferenceField.get_backreferences_for
|
train
|
def get_backreferences_for(self, instance):
"""Returns the backreferences for the given instance
:returns: list of UIDs
"""
rc = api.get_tool("reference_catalog")
backreferences = rc.getReferences(instance, self.relationship)
return map(lambda ref: ref.targetUID, backreferences)
|
python
|
{
"resource": ""
}
|
q21133
|
HistoryAwareReferenceField.preprocess_value
|
train
|
def preprocess_value(self, value, default=tuple()):
"""Preprocess the value for set
"""
# empty value
if not value:
return default
# list with one empty item
if isinstance(value, (list, tuple)):
if len(value) == 1 and not value[0]:
return default
if not isinstance(value, (list, tuple)):
value = value,
return value
|
python
|
{
"resource": ""
}
|
q21134
|
HistoryAwareReferenceField.link_version
|
train
|
def link_version(self, source, target):
"""Link the current version of the target on the source
"""
if not hasattr(target, VERSION_ID):
# no initial version of this object!
logger.warn("No iniatial version found for '{}'"
.format(repr(target)))
return
if not hasattr(source, REFERENCE_VERSIONS):
source.reference_versions = {}
target_uid = api.get_uid(target)
# store the current version of the target on the source
source.reference_versions[target_uid] = target.version_id
# persist changes that occured referenced versions
source._p_changed = 1
|
python
|
{
"resource": ""
}
|
q21135
|
HistoryAwareReferenceField.unlink_version
|
train
|
def unlink_version(self, source, target):
"""Unlink the current version of the target from the source
"""
if not hasattr(source, REFERENCE_VERSIONS):
return
target_uid = api.get_uid(target)
if target_uid in source.reference_versions[target_uid]:
# delete the version
del source.reference_versions[target_uid]
# persist changes that occured referenced versions
source._p_changed = 1
else:
logger.warn("No version link found on '{}' -> '{}'"
.format(repr(source), repr(target)))
|
python
|
{
"resource": ""
}
|
q21136
|
HistoryAwareReferenceField.add_reference
|
train
|
def add_reference(self, source, target, **kwargs):
"""Add a new reference
"""
# Tweak keyword arguments for addReference
addRef_kw = kwargs.copy()
addRef_kw.setdefault("referenceClass", self.referenceClass)
if "schema" in addRef_kw:
del addRef_kw["schema"]
uid = api.get_uid(target)
rc = api.get_tool("reference_catalog")
# throws IndexError if uid is invalid
rc.addReference(source, uid, self.relationship, **addRef_kw)
# link the version of the reference
self.link_version(source, target)
|
python
|
{
"resource": ""
}
|
q21137
|
HistoryAwareReferenceField.del_reference
|
train
|
def del_reference(self, source, target, **kwargs):
"""Remove existing reference
"""
rc = api.get_tool("reference_catalog")
uid = api.get_uid(target)
rc.deleteReference(source, uid, self.relationship)
# unlink the version of the reference
self.link_version(source, target)
|
python
|
{
"resource": ""
}
|
q21138
|
AddAnalysesView.folderitems
|
train
|
def folderitems(self):
"""Return folderitems as brains
"""
items = super(AddAnalysesView, self).folderitems(classic=False)
return items
|
python
|
{
"resource": ""
}
|
q21139
|
AddAnalysesView.getWorksheetTemplates
|
train
|
def getWorksheetTemplates(self):
"""Return WS Templates
"""
vocabulary = CatalogVocabulary(self)
vocabulary.catalog = "bika_setup_catalog"
return vocabulary(
portal_type="WorksheetTemplate", sort_on="sortable_title")
|
python
|
{
"resource": ""
}
|
q21140
|
AnalysisRequestViewView.render_analyses_table
|
train
|
def render_analyses_table(self, table="lab"):
"""Render Analyses Table
"""
if table not in ["lab", "field", "qc"]:
raise KeyError("Table '{}' does not exist".format(table))
view_name = "table_{}_analyses".format(table)
view = api.get_view(
view_name, context=self.context, request=self.request)
# Call listing hooks
view.update()
view.before_render()
return view.ajax_contents_table()
|
python
|
{
"resource": ""
}
|
q21141
|
get_meta_value_for
|
train
|
def get_meta_value_for(snapshot, key, default=None):
"""Returns the metadata value for the given key
"""
metadata = get_snapshot_metadata(snapshot)
return metadata.get(key, default)
|
python
|
{
"resource": ""
}
|
q21142
|
get_fullname
|
train
|
def get_fullname(snapshot):
"""Get the actor's fullname of the snapshot
"""
actor = get_actor(snapshot)
properties = api.get_user_properties(actor)
return properties.get("fullname", actor)
|
python
|
{
"resource": ""
}
|
q21143
|
listing_searchable_text
|
train
|
def listing_searchable_text(instance):
"""Fulltext search for the audit metadata
"""
# get all snapshots
snapshots = get_snapshots(instance)
# extract all snapshot values, because we are not interested in the
# fieldnames (keys)
values = map(lambda s: s.values(), snapshots)
# prepare a set of unified catalog data
catalog_data = set()
# values to skip
skip_values = ["None", "true", "True", "false", "False"]
# internal uid -> title cache
uid_title_cache = {}
# helper function to recursively unpack the snapshot values
def append(value):
if isinstance(value, (list, tuple)):
map(append, value)
elif isinstance(value, (dict)):
map(append, value.items())
elif isinstance(value, basestring):
# convert unicode to UTF8
if isinstance(value, unicode):
value = api.safe_unicode(value).encode("utf8")
# skip single short values
if len(value) < 2:
return
# flush non meaningful values
if value in skip_values:
return
# flush ISO dates
if re.match(DATE_RX, value):
return
# fetch the title
if re.match(UID_RX, value):
if value in uid_title_cache:
value = uid_title_cache[value]
else:
title_or_id = get_title_or_id_from_uid(value)
uid_title_cache[value] = title_or_id
value = title_or_id
catalog_data.add(value)
# extract all meaningful values
for value in itertools.chain(values):
append(value)
return " ".join(catalog_data)
|
python
|
{
"resource": ""
}
|
q21144
|
snapshot_created
|
train
|
def snapshot_created(instance):
"""Snapshot created date
"""
last_snapshot = get_last_snapshot(instance)
snapshot_created = get_created(last_snapshot)
return api.to_date(snapshot_created)
|
python
|
{
"resource": ""
}
|
q21145
|
InstrumentCalibration.isCalibrationInProgress
|
train
|
def isCalibrationInProgress(self):
"""Checks if the current date is between a calibration period.
"""
today = DateTime()
down_from = self.getDownFrom()
down_to = self.getDownTo()
return down_from <= today <= down_to
|
python
|
{
"resource": ""
}
|
q21146
|
InstrumentScheduledTask.getTaskTypes
|
train
|
def getTaskTypes(self):
""" Return the current list of task types
"""
types = [
('Calibration', safe_unicode(_('Calibration')).encode('utf-8')),
('Enhancement', safe_unicode(_('Enhancement')).encode('utf-8')),
('Preventive', safe_unicode(_('Preventive')).encode('utf-8')),
('Repair', safe_unicode(_('Repair')).encode('utf-8')),
('Validation', safe_unicode(_('Validation')).encode('utf-8')),
]
return DisplayList(types)
|
python
|
{
"resource": ""
}
|
q21147
|
AnalysesTransposedView.get_slots
|
train
|
def get_slots(self):
"""Return the current used analyses positions
"""
positions = map(
lambda uid: self.get_item_slot(uid), self.get_analyses_uids())
return map(lambda pos: str(pos), sorted(set(positions)))
|
python
|
{
"resource": ""
}
|
q21148
|
Person.getFullname
|
train
|
def getFullname(self):
"""Person's Fullname
"""
fn = self.getFirstname()
mi = self.getMiddleinitial()
md = self.getMiddlename()
sn = self.getSurname()
fullname = ""
if fn or sn:
if mi and md:
fullname = "%s %s %s %s" % (
self.getFirstname(),
self.getMiddleinitial(),
self.getMiddlename(),
self.getSurname())
elif mi:
fullname = "%s %s %s" % (
self.getFirstname(),
self.getMiddleinitial(),
self.getSurname())
elif md:
fullname = "%s %s %s" % (
self.getFirstname(),
self.getMiddlename(),
self.getSurname())
else:
fullname = '%s %s' % (self.getFirstname(), self.getSurname())
return fullname.strip()
|
python
|
{
"resource": ""
}
|
q21149
|
AnalysisServiceInfoView.get_currency_symbol
|
train
|
def get_currency_symbol(self):
"""Get the currency Symbol
"""
locale = locales.getLocale('en')
setup = api.get_setup()
currency = setup.getCurrency()
return locale.numbers.currencies[currency].symbol
|
python
|
{
"resource": ""
}
|
q21150
|
AnalysisServiceInfoView.analysis_log_view
|
train
|
def analysis_log_view(self):
"""Get the log view of the requested analysis
"""
service = self.get_analysis_or_service()
if not self.can_view_logs_of(service):
return None
view = api.get_view("auditlog", context=service, request=self.request)
view.update()
view.before_render()
return view
|
python
|
{
"resource": ""
}
|
q21151
|
get_record_value
|
train
|
def get_record_value(request, uid, keyword, default=None):
"""Returns the value for the keyword and uid from the request"""
value = request.get(keyword)
if not value:
return default
if not isinstance(value, list):
return default
return value[0].get(uid, default) or default
|
python
|
{
"resource": ""
}
|
q21152
|
_sumLists
|
train
|
def _sumLists(a, b):
"""
Algorithm to check validity of NBI and NIF.
Receives string with a umber to validate.
"""
val = 0
for i in map(lambda a, b: a * b, a, b):
val += i
return val
|
python
|
{
"resource": ""
}
|
q21153
|
UniqueFieldValidator.get_parent_objects
|
train
|
def get_parent_objects(self, context):
"""Return all objects of the same type from the parent object
"""
parent_object = api.get_parent(context)
portal_type = api.get_portal_type(context)
return parent_object.objectValues(portal_type)
|
python
|
{
"resource": ""
}
|
q21154
|
UniqueFieldValidator.query_parent_objects
|
train
|
def query_parent_objects(self, context, query=None):
"""Return the objects of the same type from the parent object
:param query: Catalog query to narrow down the objects
:type query: dict
:returns: Content objects of the same portal type in the parent
"""
# return the object values if we have no catalog query
if query is None:
return self.get_parent_objects(context)
# avoid undefined reference of catalog in except...
catalog = None
# try to fetch the results via the catalog
try:
catalogs = api.get_catalogs_for(context)
catalog = catalogs[0]
return map(api.get_object, catalog(query))
except (IndexError, UnicodeDecodeError, ParseError, APIError) as e:
# fall back to the object values of the parent
logger.warn("UniqueFieldValidator: Catalog query {} failed "
"for catalog {} ({}) -> returning object values of {}"
.format(query, repr(catalog), str(e),
repr(api.get_parent(context))))
return self.get_parent_objects(context)
|
python
|
{
"resource": ""
}
|
q21155
|
UniqueFieldValidator.make_catalog_query
|
train
|
def make_catalog_query(self, context, field, value):
"""Create a catalog query for the field
"""
# get the catalogs for the context
catalogs = api.get_catalogs_for(context)
# context not in any catalog?
if not catalogs:
logger.warn("UniqueFieldValidator: Context '{}' is not assigned"
"to any catalog!".format(repr(context)))
return None
# take the first catalog
catalog = catalogs[0]
# Check if the field accessor is indexed
field_index = field.getName()
accessor = field.getAccessor(context)
if accessor:
field_index = accessor.__name__
# return if the field is not indexed
if field_index not in catalog.indexes():
return None
# build a catalog query
query = {
"portal_type": api.get_portal_type(context),
"path": {
"query": api.get_parent_path(context),
"depth": 1,
}
}
query[field_index] = value
logger.info("UniqueFieldValidator:Query={}".format(query))
return query
|
python
|
{
"resource": ""
}
|
q21156
|
Organisation.Title
|
train
|
def Title(self):
"""Return the name of the Organisation
"""
field = self.getField("Name")
field = field and field.get(self) or ""
return safe_unicode(field).encode("utf-8")
|
python
|
{
"resource": ""
}
|
q21157
|
Organisation.getPrintAddress
|
train
|
def getPrintAddress(self):
"""Get an address for printing
"""
address_lines = []
addresses = [
self.getPostalAddress(),
self.getPhysicalAddress(),
self.getBillingAddress(),
]
for address in addresses:
city = address.get("city", "")
zip = address.get("zip", "")
state = address.get("state", "")
country = address.get("country", "")
if city:
address_lines = [
address["address"].strip(),
"{} {}".format(city, zip).strip(),
"{} {}".format(state, country).strip(),
]
break
return address_lines
|
python
|
{
"resource": ""
}
|
q21158
|
create
|
train
|
def create(container, portal_type, *args, **kwargs):
"""Creates an object in Bika LIMS
This code uses most of the parts from the TypesTool
see: `Products.CMFCore.TypesTool._constructInstance`
:param container: container
:type container: ATContentType/DexterityContentType/CatalogBrain
:param portal_type: The portal type to create, e.g. "Client"
:type portal_type: string
:param title: The title for the new content object
:type title: string
:returns: The new created object
"""
from bika.lims.utils import tmpID
if kwargs.get("title") is None:
kwargs["title"] = "New {}".format(portal_type)
# generate a temporary ID
tmp_id = tmpID()
# get the fti
types_tool = get_tool("portal_types")
fti = types_tool.getTypeInfo(portal_type)
if fti.product:
obj = _createObjectByType(portal_type, container, tmp_id)
else:
# newstyle factory
factory = getUtility(IFactory, fti.factory)
obj = factory(tmp_id, *args, **kwargs)
if hasattr(obj, '_setPortalTypeName'):
obj._setPortalTypeName(fti.getId())
notify(ObjectCreatedEvent(obj))
# notifies ObjectWillBeAddedEvent, ObjectAddedEvent and
# ContainerModifiedEvent
container._setObject(tmp_id, obj)
# we get the object here with the current object id, as it might be
# renamed already by an event handler
obj = container._getOb(obj.getId())
# handle AT Content
if is_at_content(obj):
obj.processForm()
# Edit after processForm; processForm does AT unmarkCreationFlag.
obj.edit(**kwargs)
# explicit notification
modified(obj)
return obj
|
python
|
{
"resource": ""
}
|
q21159
|
get_tool
|
train
|
def get_tool(name, context=None, default=_marker):
"""Get a portal tool by name
:param name: The name of the tool, e.g. `portal_catalog`
:type name: string
:param context: A portal object
:type context: ATContentType/DexterityContentType/CatalogBrain
:returns: Portal Tool
"""
# Try first with the context
if context is not None:
try:
context = get_object(context)
return getToolByName(context, name)
except (APIError, AttributeError) as e:
# https://github.com/senaite/bika.lims/issues/396
logger.warn("get_tool::getToolByName({}, '{}') failed: {} "
"-> falling back to plone.api.portal.get_tool('{}')"
.format(repr(context), name, repr(e), name))
return get_tool(name, default=default)
# Try with the plone api
try:
return ploneapi.portal.get_tool(name)
except InvalidParameterError:
if default is not _marker:
return default
fail("No tool named '%s' found." % name)
|
python
|
{
"resource": ""
}
|
q21160
|
is_object
|
train
|
def is_object(brain_or_object):
"""Check if the passed in object is a supported portal content object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: Portal Object
:returns: True if the passed in object is a valid portal content
"""
if is_portal(brain_or_object):
return True
if is_at_content(brain_or_object):
return True
if is_dexterity_content(brain_or_object):
return True
if is_brain(brain_or_object):
return True
return False
|
python
|
{
"resource": ""
}
|
q21161
|
is_folderish
|
train
|
def is_folderish(brain_or_object):
"""Checks if the passed in object is folderish
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: True if the object is folderish
:rtype: bool
"""
if hasattr(brain_or_object, "is_folderish"):
if callable(brain_or_object.is_folderish):
return brain_or_object.is_folderish()
return brain_or_object.is_folderish
return IFolderish.providedBy(get_object(brain_or_object))
|
python
|
{
"resource": ""
}
|
q21162
|
get_portal_type
|
train
|
def get_portal_type(brain_or_object):
"""Get the portal type for this object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Portal type
:rtype: string
"""
if not is_object(brain_or_object):
fail("{} is not supported.".format(repr(brain_or_object)))
return brain_or_object.portal_type
|
python
|
{
"resource": ""
}
|
q21163
|
get_schema
|
train
|
def get_schema(brain_or_object):
"""Get the schema of the content
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Schema object
"""
obj = get_object(brain_or_object)
if is_portal(obj):
fail("get_schema can't return schema of portal root")
if is_dexterity_content(obj):
pt = get_tool("portal_types")
fti = pt.getTypeInfo(obj.portal_type)
return fti.lookupSchema()
if is_at_content(obj):
return obj.Schema()
fail("{} has no Schema.".format(brain_or_object))
|
python
|
{
"resource": ""
}
|
q21164
|
get_id
|
train
|
def get_id(brain_or_object):
"""Get the Plone ID for this object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Plone ID
:rtype: string
"""
if is_brain(brain_or_object) and base_hasattr(brain_or_object, "getId"):
return brain_or_object.getId
return get_object(brain_or_object).getId()
|
python
|
{
"resource": ""
}
|
q21165
|
get_url
|
train
|
def get_url(brain_or_object):
"""Get the absolute URL for this object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Absolute URL
:rtype: string
"""
if is_brain(brain_or_object) and base_hasattr(brain_or_object, "getURL"):
return brain_or_object.getURL()
return get_object(brain_or_object).absolute_url()
|
python
|
{
"resource": ""
}
|
q21166
|
get_brain_by_uid
|
train
|
def get_brain_by_uid(uid, default=None):
"""Query a brain by a given UID
:param uid: The UID of the object to find
:type uid: string
:returns: ZCatalog brain or None
"""
if not is_uid(uid):
return default
# we try to find the object with the UID catalog
uc = get_tool("uid_catalog")
# try to find the object with the reference catalog first
brains = uc(UID=uid)
if len(brains) != 1:
return default
return brains[0]
|
python
|
{
"resource": ""
}
|
q21167
|
get_parent_path
|
train
|
def get_parent_path(brain_or_object):
"""Calculate the physical parent path of this object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Physical path of the parent object
:rtype: string
"""
if is_portal(brain_or_object):
return get_path(get_portal())
if is_brain(brain_or_object):
path = get_path(brain_or_object)
return path.rpartition("/")[0]
return get_path(get_object(brain_or_object).aq_parent)
|
python
|
{
"resource": ""
}
|
q21168
|
search
|
train
|
def search(query, catalog=_marker):
"""Search for objects.
:param query: A suitable search query.
:type query: dict
:param catalog: A single catalog id or a list of catalog ids
:type catalog: str/list
:returns: Search results
:rtype: List of ZCatalog brains
"""
# query needs to be a dictionary
if not isinstance(query, dict):
fail("Catalog query needs to be a dictionary")
# Portal types to query
portal_types = query.get("portal_type", [])
# We want the portal_type as a list
if not isinstance(portal_types, (tuple, list)):
portal_types = [portal_types]
# The catalogs used for the query
catalogs = []
# The user did **not** specify a catalog
if catalog is _marker:
# Find the registered catalogs for the queried portal types
for portal_type in portal_types:
# Just get the first registered/default catalog
catalogs.append(get_catalogs_for(
portal_type, default="portal_catalog")[0])
else:
# User defined catalogs
if isinstance(catalog, (list, tuple)):
catalogs.extend(map(get_tool, catalog))
else:
catalogs.append(get_tool(catalog))
# Cleanup: Avoid duplicate catalogs
catalogs = list(set(catalogs)) or [get_portal_catalog()]
# We only support **single** catalog queries
if len(catalogs) > 1:
fail("Multi Catalog Queries are not supported!")
return catalogs[0](query)
|
python
|
{
"resource": ""
}
|
q21169
|
safe_getattr
|
train
|
def safe_getattr(brain_or_object, attr, default=_marker):
"""Return the attribute value
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param attr: Attribute name
:type attr: str
:returns: Attribute value
:rtype: obj
"""
try:
value = getattr(brain_or_object, attr, _marker)
if value is _marker:
if default is not _marker:
return default
fail("Attribute '{}' not found.".format(attr))
if callable(value):
return value()
return value
except Unauthorized:
if default is not _marker:
return default
fail("You are not authorized to access '{}' of '{}'.".format(
attr, repr(brain_or_object)))
|
python
|
{
"resource": ""
}
|
q21170
|
get_revision_history
|
train
|
def get_revision_history(brain_or_object):
"""Get the revision history for the given brain or context.
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Workflow history
:rtype: obj
"""
obj = get_object(brain_or_object)
chv = ContentHistoryView(obj, safe_getattr(obj, "REQUEST", None))
return chv.fullHistory()
|
python
|
{
"resource": ""
}
|
q21171
|
get_workflows_for
|
train
|
def get_workflows_for(brain_or_object):
"""Get the assigned workflows for the given brain or context.
Note: This function supports also the portal_type as parameter.
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Assigned Workflows
:rtype: tuple
"""
workflow = ploneapi.portal.get_tool("portal_workflow")
if isinstance(brain_or_object, basestring):
return workflow.getChainFor(brain_or_object)
obj = get_object(brain_or_object)
return workflow.getChainFor(obj)
|
python
|
{
"resource": ""
}
|
q21172
|
get_creation_date
|
train
|
def get_creation_date(brain_or_object):
"""Get the creation date of the brain or object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Creation date
:rtype: DateTime
"""
created = getattr(brain_or_object, "created", None)
if created is None:
fail("Object {} has no creation date ".format(
repr(brain_or_object)))
if callable(created):
return created()
return created
|
python
|
{
"resource": ""
}
|
q21173
|
get_modification_date
|
train
|
def get_modification_date(brain_or_object):
"""Get the modification date of the brain or object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Modification date
:rtype: DateTime
"""
modified = getattr(brain_or_object, "modified", None)
if modified is None:
fail("Object {} has no modification date ".format(
repr(brain_or_object)))
if callable(modified):
return modified()
return modified
|
python
|
{
"resource": ""
}
|
q21174
|
get_catalogs_for
|
train
|
def get_catalogs_for(brain_or_object, default="portal_catalog"):
"""Get all registered catalogs for the given portal_type, catalog brain or
content object
:param brain_or_object: The portal_type, a catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: List of supported catalogs
:rtype: list
"""
archetype_tool = get_tool("archetype_tool", None)
if not archetype_tool:
# return the default catalog
return [get_tool(default)]
catalogs = []
# get the registered catalogs for portal_type
if is_object(brain_or_object):
catalogs = archetype_tool.getCatalogsByType(
get_portal_type(brain_or_object))
if isinstance(brain_or_object, basestring):
catalogs = archetype_tool.getCatalogsByType(brain_or_object)
if not catalogs:
return [get_tool(default)]
return catalogs
|
python
|
{
"resource": ""
}
|
q21175
|
get_transitions_for
|
train
|
def get_transitions_for(brain_or_object):
"""List available workflow transitions for all workflows
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: All possible available and allowed transitions
:rtype: list[dict]
"""
workflow = get_tool('portal_workflow')
transitions = []
instance = get_object(brain_or_object)
for wfid in get_workflows_for(brain_or_object):
wf = workflow[wfid]
tlist = wf.getTransitionsFor(instance)
transitions.extend([t for t in tlist if t not in transitions])
return transitions
|
python
|
{
"resource": ""
}
|
q21176
|
get_roles_for_permission
|
train
|
def get_roles_for_permission(permission, brain_or_object):
"""Get a list of granted roles for the given permission on the object.
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Roles for the given Permission
:rtype: list
"""
obj = get_object(brain_or_object)
allowed = set(rolesForPermissionOn(permission, obj))
return sorted(allowed)
|
python
|
{
"resource": ""
}
|
q21177
|
is_versionable
|
train
|
def is_versionable(brain_or_object, policy='at_edit_autoversion'):
"""Checks if the passed in object is versionable.
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: True if the object is versionable
:rtype: bool
"""
pr = get_tool("portal_repository")
obj = get_object(brain_or_object)
return pr.supportsPolicy(obj, 'at_edit_autoversion') \
and pr.isVersionable(obj)
|
python
|
{
"resource": ""
}
|
q21178
|
get_version
|
train
|
def get_version(brain_or_object):
"""Get the version of the current object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: The current version of the object, or None if not available
:rtype: int or None
"""
obj = get_object(brain_or_object)
if not is_versionable(obj):
return None
return getattr(aq_base(obj), "version_id", 0)
|
python
|
{
"resource": ""
}
|
q21179
|
get_view
|
train
|
def get_view(name, context=None, request=None):
"""Get the view by name
:param name: The name of the view
:type name: str
:param context: The context to query the view
:type context: ATContentType/DexterityContentType/CatalogBrain
:param request: The request to query the view
:type request: HTTPRequest object
:returns: HTTP Request
:rtype: Products.Five.metaclass View object
"""
context = context or get_portal()
request = request or get_request() or None
return getMultiAdapter((get_object(context), request), name=name)
|
python
|
{
"resource": ""
}
|
q21180
|
get_group
|
train
|
def get_group(group_or_groupname):
"""Return Plone Group
:param group_or_groupname: Plone group or the name of the group
:type groupname: GroupData/str
:returns: Plone GroupData
"""
if not group_or_groupname:
return None
if hasattr(group_or_groupname, "_getGroup"):
return group_or_groupname
gtool = get_tool("portal_groups")
return gtool.getGroupById(group_or_groupname)
|
python
|
{
"resource": ""
}
|
q21181
|
get_user_properties
|
train
|
def get_user_properties(user_or_username):
"""Return User Properties
:param user_or_username: Plone group identifier
:returns: Plone MemberData
"""
user = get_user(user_or_username)
if user is None:
return {}
if not callable(user.getUser):
return {}
out = {}
plone_user = user.getUser()
for sheet in plone_user.listPropertysheets():
ps = plone_user.getPropertysheet(sheet)
out.update(dict(ps.propertyItems()))
return out
|
python
|
{
"resource": ""
}
|
q21182
|
get_users_by_roles
|
train
|
def get_users_by_roles(roles=None):
"""Search Plone users by their roles
:param roles: Plone role name or list of roles
:type roles: list/str
:returns: List of Plone users having the role(s)
"""
if not isinstance(roles, (tuple, list)):
roles = [roles]
mtool = get_tool("portal_membership")
return mtool.searchForMembers(roles=roles)
|
python
|
{
"resource": ""
}
|
q21183
|
get_user_contact
|
train
|
def get_user_contact(user, contact_types=['Contact', 'LabContact']):
"""Returns the associated contact of a Plone user
If the user passed in has no contact associated, return None.
The `contact_types` parameter filter the portal types for the search.
:param: Plone user
:contact_types: List with the contact portal types to search
:returns: Contact associated to the Plone user or None
"""
if not user:
return None
query = {'portal_type': contact_types, 'getUsername': user.id}
brains = search(query, catalog='portal_catalog')
if not brains:
return None
if len(brains) > 1:
# Oops, the user has multiple contacts assigned, return None
contacts = map(lambda c: c.Title, brains)
err_msg = "User '{}' is bound to multiple Contacts '{}'"
err_msg = err_msg.format(user.id, ','.join(contacts))
logger.error(err_msg)
return None
return get_object(brains[0])
|
python
|
{
"resource": ""
}
|
q21184
|
get_user_client
|
train
|
def get_user_client(user_or_contact):
"""Returns the client of the contact of a Plone user
If the user passed in has no contact or does not belong to any client,
returns None.
:param: Plone user or contact
:returns: Client the contact of the Plone user belongs to
"""
if not user_or_contact or ILabContact.providedBy(user_or_contact):
# Lab contacts cannot belong to a client
return None
if not IContact.providedBy(user_or_contact):
contact = get_user_contact(user_or_contact, contact_types=['Contact'])
if IContact.providedBy(contact):
return get_user_client(contact)
return None
client = get_parent(user_or_contact)
if client and IClient.providedBy(client):
return client
return None
|
python
|
{
"resource": ""
}
|
q21185
|
get_cache_key
|
train
|
def get_cache_key(brain_or_object):
"""Generate a cache key for a common brain or object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Cache Key
:rtype: str
"""
key = [
get_portal_type(brain_or_object),
get_id(brain_or_object),
get_uid(brain_or_object),
# handle different domains gracefully
get_url(brain_or_object),
# Return the microsecond since the epoch in GMT
get_modification_date(brain_or_object).micros(),
]
return "-".join(map(lambda x: str(x), key))
|
python
|
{
"resource": ""
}
|
q21186
|
normalize_id
|
train
|
def normalize_id(string):
"""Normalize the id
:param string: A string to normalize
:type string: str
:returns: Normalized ID
:rtype: str
"""
if not isinstance(string, basestring):
fail("Type of argument must be string, found '{}'"
.format(type(string)))
# get the id nomalizer utility
normalizer = getUtility(IIDNormalizer).normalize
return normalizer(string)
|
python
|
{
"resource": ""
}
|
q21187
|
normalize_filename
|
train
|
def normalize_filename(string):
"""Normalize the filename
:param string: A string to normalize
:type string: str
:returns: Normalized ID
:rtype: str
"""
if not isinstance(string, basestring):
fail("Type of argument must be string, found '{}'"
.format(type(string)))
# get the file nomalizer utility
normalizer = getUtility(IFileNameNormalizer).normalize
return normalizer(string)
|
python
|
{
"resource": ""
}
|
q21188
|
to_minutes
|
train
|
def to_minutes(days=0, hours=0, minutes=0, seconds=0, milliseconds=0,
round_to_int=True):
"""Returns the computed total number of minutes
"""
total = float(days)*24*60 + float(hours)*60 + float(minutes) + \
float(seconds)/60 + float(milliseconds)/1000/60
return int(round(total)) if round_to_int else total
|
python
|
{
"resource": ""
}
|
q21189
|
to_dhm_format
|
train
|
def to_dhm_format(days=0, hours=0, minutes=0, seconds=0, milliseconds=0):
"""Returns a representation of time in a string in xd yh zm format
"""
minutes = to_minutes(days=days, hours=hours, minutes=minutes,
seconds=seconds, milliseconds=milliseconds)
delta = timedelta(minutes=int(round(minutes)))
d = delta.days
h = delta.seconds // 3600
m = (delta.seconds // 60) % 60
m = m and "{}m ".format(str(m)) or ""
d = d and "{}d ".format(str(d)) or ""
if m and d:
h = "{}h ".format(str(h))
else:
h = h and "{}h ".format(str(h)) or ""
return "".join([d, h, m]).strip()
|
python
|
{
"resource": ""
}
|
q21190
|
to_int
|
train
|
def to_int(value, default=_marker):
"""Tries to convert the value to int.
Truncates at the decimal point if the value is a float
:param value: The value to be converted to an int
:return: The resulting int or default
"""
if is_floatable(value):
value = to_float(value)
try:
return int(value)
except (TypeError, ValueError):
if default is None:
return default
if default is not _marker:
return to_int(default)
fail("Value %s cannot be converted to int" % repr(value))
|
python
|
{
"resource": ""
}
|
q21191
|
to_float
|
train
|
def to_float(value, default=_marker):
"""Converts the passed in value to a float number
:param value: The value to be converted to a floatable number
:type value: str, float, int
:returns: The float number representation of the passed in value
:rtype: float
"""
if not is_floatable(value):
if default is not _marker:
return to_float(default)
fail("Value %s is not floatable" % repr(value))
return float(value)
|
python
|
{
"resource": ""
}
|
q21192
|
to_searchable_text_metadata
|
train
|
def to_searchable_text_metadata(value):
"""Parse the given metadata value to searchable text
:param value: The raw value of the metadata column
:returns: Searchable and translated unicode value or None
"""
if not value:
return u""
if value is Missing.Value:
return u""
if is_uid(value):
return u""
if isinstance(value, (bool)):
return u""
if isinstance(value, (list, tuple)):
for v in value:
return to_searchable_text_metadata(v)
if isinstance(value, (dict)):
for k, v in value.items():
return to_searchable_text_metadata(v)
if is_date(value):
return value.strftime("%Y-%m-%d")
if not isinstance(value, basestring):
value = str(value)
return safe_unicode(value)
|
python
|
{
"resource": ""
}
|
q21193
|
to_display_list
|
train
|
def to_display_list(pairs, sort_by="key", allow_empty=True):
"""Create a Plone DisplayList from list items
:param pairs: list of key, value pairs
:param sort_by: Sort the items either by key or value
:param allow_empty: Allow to select an empty value
:returns: Plone DisplayList
"""
dl = DisplayList()
if isinstance(pairs, basestring):
pairs = [pairs, pairs]
for pair in pairs:
# pairs is a list of lists -> add each pair
if isinstance(pair, (tuple, list)):
dl.add(*pair)
# pairs is just a single pair -> add it and stop
if isinstance(pair, basestring):
dl.add(*pairs)
break
# add the empty option
if allow_empty:
dl.add("", "")
# sort by key/value
if sort_by == "key":
dl = dl.sortedByKey()
elif sort_by == "value":
dl = dl.sortedByValue()
return dl
|
python
|
{
"resource": ""
}
|
q21194
|
AnalysesView.has_permission
|
train
|
def has_permission(self, permission, obj=None):
"""Returns if the current user has rights for the permission passed in
:param permission: permission identifier
:param obj: object to check the permission against
:return: True if the user has rights for the permission passed in
"""
if not permission:
logger.warn("None permission is not allowed")
return False
if obj is None:
return check_permission(permission, self.context)
return check_permission(permission, api.get_object(obj))
|
python
|
{
"resource": ""
}
|
q21195
|
AnalysesView.is_analysis_edition_allowed
|
train
|
def is_analysis_edition_allowed(self, analysis_brain):
"""Returns if the analysis passed in can be edited by the current user
:param analysis_brain: Brain that represents an analysis
:return: True if the user can edit the analysis, otherwise False
"""
if not self.context_active:
# The current context must be active. We cannot edit analyses from
# inside a deactivated Analysis Request, for instance
return False
analysis_obj = api.get_object(analysis_brain)
if analysis_obj.getPointOfCapture() == 'field':
# This analysis must be captured on field, during sampling.
if not self.has_permission(EditFieldResults, analysis_obj):
# Current user cannot edit field analyses.
return False
elif not self.has_permission(EditResults, analysis_obj):
# The Point of Capture is 'lab' and the current user cannot edit
# lab analyses.
return False
# Check if the user is allowed to enter a value to to Result field
if not self.has_permission(FieldEditAnalysisResult, analysis_obj):
return False
# Is the instrument out of date?
# The user can assign a result to the analysis if it does not have any
# instrument assigned or the instrument assigned is valid.
if not self.is_analysis_instrument_valid(analysis_brain):
# return if it is allowed to enter a manual result
return analysis_obj.getManualEntryOfResults()
return True
|
python
|
{
"resource": ""
}
|
q21196
|
AnalysesView.is_result_edition_allowed
|
train
|
def is_result_edition_allowed(self, analysis_brain):
"""Checks if the edition of the result field is allowed
:param analysis_brain: Brain that represents an analysis
:return: True if the user can edit the result field, otherwise False
"""
# Always check general edition first
if not self.is_analysis_edition_allowed(analysis_brain):
return False
# Get the ananylsis object
obj = api.get_object(analysis_brain)
if not obj.getDetectionLimitOperand():
# This is a regular result (not a detection limit)
return True
# Detection limit selector is enabled in the Analysis Service
if obj.getDetectionLimitSelector():
# Manual detection limit entry is *not* allowed
if not obj.getAllowManualDetectionLimit():
return False
return True
|
python
|
{
"resource": ""
}
|
q21197
|
AnalysesView.is_uncertainty_edition_allowed
|
train
|
def is_uncertainty_edition_allowed(self, analysis_brain):
"""Checks if the edition of the uncertainty field is allowed
:param analysis_brain: Brain that represents an analysis
:return: True if the user can edit the result field, otherwise False
"""
# Only allow to edit the uncertainty if result edition is allowed
if not self.is_result_edition_allowed(analysis_brain):
return False
# Get the ananylsis object
obj = api.get_object(analysis_brain)
# Manual setting of uncertainty is not allowed
if not obj.getAllowManualUncertainty():
return False
# Result is a detection limit -> uncertainty setting makes no sense!
if obj.getDetectionLimitOperand() in [LDL, UDL]:
return False
return True
|
python
|
{
"resource": ""
}
|
q21198
|
AnalysesView.is_analysis_instrument_valid
|
train
|
def is_analysis_instrument_valid(self, analysis_brain):
"""Return if the analysis has a valid instrument.
If the analysis passed in is from ReferenceAnalysis type or does not
have an instrument assigned, returns True
:param analysis_brain: Brain that represents an analysis
:return: True if the instrument assigned is valid or is None"""
if analysis_brain.meta_type == 'ReferenceAnalysis':
# If this is a ReferenceAnalysis, there is no need to check the
# validity of the instrument, because this is a QC analysis and by
# definition, it has the ability to promote an instrument to a
# valid state if the result is correct.
return True
instrument = self.get_instrument(analysis_brain)
return not instrument or instrument.isValid()
|
python
|
{
"resource": ""
}
|
q21199
|
AnalysesView.get_object
|
train
|
def get_object(self, brain_or_object_or_uid):
"""Get the full content object. Returns None if the param passed in is
not a valid, not a valid object or not found
:param brain_or_object_or_uid: UID/Catalog brain/content object
:returns: content object
"""
if api.is_uid(brain_or_object_or_uid):
return api.get_object_by_uid(brain_or_object_or_uid, default=None)
if api.is_object(brain_or_object_or_uid):
return api.get_object(brain_or_object_or_uid)
return None
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.