_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | 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] = []
| python | {
"resource": ""
} |
q21101 | do_action_to_ancestors | train | def do_action_to_ancestors(analysis_request, transition_id):
"""Promotes the transitiion passed in to | python | {
"resource": ""
} |
q21102 | do_action_to_descendants | train | def do_action_to_descendants(analysis_request, transition_id):
"""Cascades the transition passed in to the | 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:
| 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
| 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' % (
| 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 = | 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
| 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:
| python | {
"resource": ""
} |
q21109 | Contact.getUser | train | def getUser(self):
"""Returns the linked Plone User or None
"""
username = self.getUsername()
if not username:
| 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)
| 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 | 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})
| 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)
| 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")
| 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")
| 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":
| 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":
| 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"):
| 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__)
| 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): | 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)
| python | {
"resource": ""
} |
q21122 | WorksheetTemplate._getMethodsVoc | train | def _getMethodsVoc(self):
"""Return the registered methods as DisplayList
"""
methods = api.search({
"portal_type": "Method",
"is_active": True
| 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:
| 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() | 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", "")
| 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, | 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)
| 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)
| 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):
| 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)
| 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
| 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
| 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)):
| 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)
| 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]
| 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 = | 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)
| python | {
"resource": ""
} |
q21138 | AddAnalysesView.folderitems | train | def folderitems(self):
"""Return folderitems as brains
| python | {
"resource": ""
} |
q21139 | AddAnalysesView.getWorksheetTemplates | train | def getWorksheetTemplates(self):
"""Return WS Templates
"""
vocabulary = CatalogVocabulary(self)
vocabulary.catalog = "bika_setup_catalog"
| 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, | python | {
"resource": ""
} |
q21141 | get_meta_value_for | train | def get_meta_value_for(snapshot, key, default=None):
"""Returns the metadata value | python | {
"resource": ""
} |
q21142 | get_fullname | train | def get_fullname(snapshot):
"""Get the actor's fullname of the snapshot
"""
actor = get_actor(snapshot)
| 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
| python | {
"resource": ""
} |
q21144 | snapshot_created | train | def snapshot_created(instance):
"""Snapshot created date
"""
last_snapshot | python | {
"resource": ""
} |
q21145 | InstrumentCalibration.isCalibrationInProgress | train | def isCalibrationInProgress(self):
"""Checks if the current date is between a calibration period.
| 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')),
| python | {
"resource": ""
} |
q21147 | AnalysesTransposedView.get_slots | train | def get_slots(self):
"""Return the current used analyses positions
"""
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())
| 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()
| 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()
| 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:
| 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 | 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 = | 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]
| 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__ | python | {
"resource": ""
} |
q21156 | Organisation.Title | train | def Title(self):
"""Return the name of the Organisation
"""
field = self.getField("Name")
| 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:
| 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()
| 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: {} "
| 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 | 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"):
| 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
| 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):
| 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
""" | 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
""" | 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 | 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):
| 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]
| 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
| 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: | 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: | 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:
| 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:
| 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):
| 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) | 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 | 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 | 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
| 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
| 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 | 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 {}
| 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)
"""
| 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:
| 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): | 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
| 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 | 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 '{}'"
| 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 + | 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
| 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:
| 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):
| 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)):
| 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)
# | 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
"""
| 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 | 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) | 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
| 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
| 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):
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.